PythonGStreamer: Difference between revisions

From XPUB & Lens-Based wiki
Line 33: Line 33:
== A command-line spectrum analyzer ==
== A command-line spectrum analyzer ==


[[Media:Spectrum.zip]]
[[Spectrum.py]]
 
<source lang="python">
import pygst
pygst.require("0.10")
import gst, gobject
import time, thread
 
class Spectrum:
 
def __init__(self):
# Create a gstreamer pipeline, listen to it's messages via on_message callback
# listener_desc = 'alsasrc ! spectrum ! fakesink'
listener_desc = 'alsasrc ! spectrum bands=64 ! fakesink'
self.listener = gst.parse_launch(listener_desc)
bus = self.listener.get_bus()
bus.add_signal_watch()
bus.connect("message", self.on_message)
 
def on_message (self, bus, message):
""" callback function for gstreamer messages """
s = message.structure
# print "message.name", s.get_name()
# print "message.structure.keys", s.keys()
if s and s.get_name() == "spectrum":
# spectrum messages have 'endtime', 'timestamp', 'stream-time', 'running-time', 'duration', 'magnitude'
# print len(s['magnitude'])
print "data: " + " ".join([str(x) for x in s['magnitude']])
return True
 
def start(self):
self.listener.set_state(gst.STATE_PLAYING)
while True:
time.sleep(1)
 
 
# Run the Spectrum object in it's own thread, then start the gobject.MainLoop as required
spectrum = Spectrum()
thread.start_new_thread(spectrum.start, ())
gobject.threads_init()
loop = gobject.MainLoop()
loop.run()
</source>


== Other Examples ==
== Other Examples ==
* [[ListeningAndWatching]]
* [[ListeningAndWatching]]

Revision as of 12:40, 1 June 2009

Using Python to program GStreamer

Generating random tones

A python random oscillator stream:

import pygst
pygst.require("0.10")
import gst

pipeline = gst.Pipeline("mypipeline")
audiotestsrc = gst.element_factory_make("audiotestsrc", "audio")
pipeline.add(audiotestsrc)
sink = gst.element_factory_make("alsasink", "sink")
pipeline.add(sink)
audiotestsrc.link(sink)
audiotestsrc.set_property("freq", 800)
pipeline.set_state(gst.STATE_PLAYING)

import time, random

while 1:
	f = random.randint(200, 800)
	print "setting freq to: %d" % f 
	audiotestsrc.set_property("freq", f)
	time.sleep(1.0/random.randint(1, 10))

A command-line level analyzer

Level.py

A command-line spectrum analyzer

Spectrum.py

Other Examples