#!/usr/bin/python
#utf8
'''
    pymusopen 0.1
    a simple stupid music player for musopen

    Julien (jvoisin) Voisin wrote this file in 2012. As long as
    you retain this notice you can do whatever you want with
    this stuff. If we meet some day, and you think
    this stuff is worth it, you can buy me a beer in return.
'''
import urllib
import re
import pygst
pygst.require('0.10')
import gst
import thread
import time
import glib, gobject
import os

class Player:
    def __init__(self):
        #creates a playbin (plays media form an uri)
        self.player = gst.element_factory_make("playbin2", "player")
        self.bus = self.player.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect('message', self.on_message)

    def get_song(self):
        '''
            Return a path to a random song
        '''
        cs = urllib.urlopen('http://www.musopen.org/playlist.php')
        m = re.search('<location>(.*)</location>', cs.read())
        song = 'http://musopen.org' + m.group(1)
        print os.path.basename(song) + '\r'
        return song

    def on_message(self, bus, msg):
        t = msg.type
        if t == gst.MESSAGE_EOS:  # end of the music
            self.playmode = False
            self.player.set_state(gst.STATE_NULL)

    def play(self):
        while 1:
            self.playmode = True
            self.player.set_property('uri', self.get_song())
            self.player.set_state(gst.STATE_PLAYING)
            while self.playmode:  # wait for the end of the song
                time.sleep(1)
        loop.quit()

mainclass = Player()
thread.start_new_thread(mainclass.play, ())
gobject.threads_init()
loop = glib.MainLoop()
loop.run()

