Playing a mp3 stream with python
I listen to web radios aka music streams alot and usually do not really care how the players work. But recently i got somehow curious about how to play a mp3 stream with python. And it should run on my windows box. That made my search a bit difficult. But i found a solution, the GStreamer lib. It has python bindings and windows builds, hurray. But actually it didn’t look like it would be a simple 1 minute installation and it wasn’t. To save you the time, i wrote this summary of my installation.
BTW if you found a better module for this task, preferably with less dependencies, i’d be happy to hear it :-)
- Python 2.6 (i assume you have it already installed :-) )
- PyGTk, somehow GStreamer needs it…
Steps for setting up the required libaries on Windows
- Download the GStreamer Windows Build and SDK
- Install them (Runtime first, SDK second)
- Download GTK+ Windows. I did use 2.16
- Install it
- Add the <gtk_folder>\bin to your PATH envrionment variable
- download and install PyGTk 2.16 for python 2.6
- download and install PyCairo 1.8 for python 2.6
- download and install PyGObject 2.20 for python 2.6
- Use this Script to verfiy PyGTK was installed successfully
If you use a different gtk+ version, make sure gtk+ and the python bindings versions match.
The Code with comments
Now we have everything set up and can finally write our first code to play a mp3 stream. I’ll just post the code with comments inside.
import pygst pygst.require("0.10") import gst def on_tag(bus, msg): taglist = msg.parse_tag() print 'on_tag:' for key in taglist.keys(): print '\t%s = %s' % (key, taglist[key]) #our stream to play music_stream_uri = 'http://mp3channels.webradio.antenne.de/chillout' #creates a playbin (plays media form an uri) player = gst.element_factory_make("playbin", "player") #set the uri player.set_property('uri', music_stream_uri) #start playing player.set_state(gst.STATE_PLAYING) #listen for tags on the message bus; tag event might be called more than once bus = player.get_bus() bus.enable_sync_message_emission() bus.add_signal_watch() bus.connect('message::tag', on_tag) #wait and let the music play raw_input('Press enter to stop playing...')
Happy hacking :-)
comments powered by Disqus