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

Required libs
  • Python 2.6 (i assume you have it already installed :-) )
  • GStreamer
  • PyGTk, somehow GStreamer needs it...
Steps for setting up the required libaries on Windows

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
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 = ''

#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

#listen for tags on the message bus; tag event might be called more than once
bus = player.get_bus()
bus.connect('message::tag', on_tag)

#wait and let the music play
raw_input('Press enter to stop playing...')

Happy hacking :-)