Search code examples
pythonpython-2.7vlclibvlc

Using VLC to play/pause an audio track inside of separate functions


I have one function (cmd_sr) that plays an audio track using the VLC-python lib.

I'm aiming to have different functions to pause, stop, change tracks, etc. But if I try to pause the track in a different function there's no change. It works fine if I add the p.pause() into the cmd_sr function.

Is there a way to embed the cmd_pause() function inside of the cmd_sr(), or somehow allow it to be accessed or paused by any function?

def cmd_sr(stream_url):
    global p
    p = vlc.MediaPlayer(stream_url)
    p.play()
def cmd_pause():
    print(stream_url)
    p = vlc.MediaPlayer(stream_url)
    sendMessage(s, "Tried to pause")
    p.pause()

Solution

  • I think that you don't need to re-create the MediaPlayer once it is created.

    One way to do that could be:

    # The player
    p = None
    
    
    def cmd_init(stream_url):
        global p
        p = vlc.MediaPlayer(stream_url)
    
    
    def cmd_sr(stream_url):
        p.play()
    
    
    def cmd_pause():
        sendMessage(s, "Tried to pause")
        p.pause()
    

    But, using a global variable (here: p) is not very elegant. The best practice is to use a class:

    class MyPlayer(object):
        def __init__(self, stream_url):
            self.player = vlc.MediaPlayer(stream_url)
    
        def play(self):
            self.player.play()
    
        def pause(self):
            sendMessage(s, "Tried to pause")
            self.player.pause()