Spectrum.py

From XPUB & Lens-Based wiki

File:Spectrum.zip

Getting the data from gstreamer

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()