Search code examples
pythonvlcpython-vlc

VLC Play/Pause For Synchronization in Python


So i am using the VLC python extension. I am trying to align playing a video with another program. Since the VLC media player has some variability of how long it takes to load the media and start playing, it can sometimes be out of alignment. I want to open/load the video in VLC, have it pause, and then wait for the trigger to play, so i can do the command back-back with another part of my program.

When i put a value into media_player.pause, the video wont play, but the other process will. If i put no value into media_player.pause(), the video will play without a pause

import time, vlc
    
# media object
media = vlc.Media('video.mp4')
  
# setting media to the media player
media_player.set_media(media)
media_player = vlc.MediaPlayer()
media_player.set_media(media)

# Play to open/load the video
media_player.play()

# Pause the Video
media_player.pause()

# Other Stuff Happens

time.sleep(init_delay)
media_player.play()

Solution

  • You need to wait for the video to load or pre-roll before it will play.
    It will not pause before it is playing.
    The simple answer is to allow the video to get to a "playing" state and then pause it.
    This can be done, simply by allowing it time to get to the playing state, by sleeping, for say 1 tenth of a second.
    You don't indicate what the activation trigger is, so in the following example, I've added a Linux friendly, keyboard trigger, that times-out after 10 seconds.

    import time, vlc
    import sys, select
        
    # media object
    media_player = vlc.MediaPlayer()
    media = vlc.Media('V1.mp4')
    vlc_playing = set([3, 4]) #  3 - Playing | 4 - Paused
    media_state = None
    # setting media to the media player
    media_player.set_media(media)
    
    # Play to open/load the video
    media_player.play()
    while media_state not in vlc_playing:
        time.sleep(0.1)
        media_state = media_player.get_state()
    
    media_player.pause()
    print("Paused - waiting for trigger")
    print("Activate trigger with Enter or Ctrl+C to terminate")
    
    #  Here the activation trigger is provide by pressing the Enter key
    #  within 10 seconds
    #  I've no idea if this will work on a Non Linux box
    #
    try:
        inp, out, err = select.select( [sys.stdin], [], [], 10 )
        if inp:
            media_player.play()
        else:
            media_state = None
    except KeyboardInterrupt:
        media_state = None
    
    if media_state: # Play loop
        while media_state in vlc_playing:
            time.sleep(1)
            try: # Cater for Ctrl+C during Play
                media_state = media_player.get_state()
            except Exception:
                media_state = None
            continue
    else:
        print("No Activation trigger - Terminated")