How to open and close omxplayer (Python/Raspberry Pi) while playing video?

后端 未结 1 1478
無奈伤痛
無奈伤痛 2020-12-22 07:10

Using a Raspberry Pi and some push buttons I want to control video playback. When someone presses a button the corresponding video plays. The buttons work great. When you pr

相关标签:
1条回答
  • 2020-12-22 07:53

    NameError: global name 'playDodgeballs' is not defined means that you are trying to use playDodgeballs before it is defined playDodgeballs = ...

    I would simplify your code by removing all globals and threads. subprocess.Popen runs a separate process; it doesn't block your main thread:

    names = 'sippycup', 'dodgeballs', 'shoppingcart'
    movies = ['Desktop/videos/{name}.mp4'.format(name=name) for name in names]
    players = [Player(movie=movie) for movie in movies]
    player = players[0]
    
    setup_io() # GPIO setup
    while True:
        for key in get_key_events(): # get GPIO input
            if key == '0':
               player = players[0]
            elif key == 'space':
               player.toggle() # pause/unpause
            elif key == 'enter':
               player.start()
            ...
    

    where Player is a simple wrapper around omxplayer subprocess:

    import logging
    from subprocess import Popen, PIPE, DEVNULL
    
    logger = logging.getLogger(__name__)
    
    class Player:
        def __init__(self, movie):
           self.movie = movie
           self.process = None
    
        def start(self):
            self.stop()
            self.process = Popen(['omxplayer', self.movie], stdin=PIPE,
                                 stdout=DEVNULL, close_fds=True, bufsize=0)
            self.process.stdin.write(start_command) # start playing
    
        def stop(self):
            p = self.process
            if p is not None:
               try:
                   p.stdin.write(quit_command) # send quit command
                   p.terminate()
                   p.wait() # -> move into background thread if necessary
               except EnvironmentError as e:
                   logger.error("can't stop %s: %s", self.movie, e)
               else:
                   self.process = None
    
        def toggle(self):
            p = self.process
            if p is not None:
               try:
                   p.stdin.write(toggle_command) # pause/unpause
               except EnvironmentError as e:
                   logger.warning("can't toggle %s: %s", self.movie, e)
    

    Specify appropriate start_command, quit_command, toggle_command. You could define different methods depending on what commands omxplayer understands and what commands you need.

    0 讨论(0)
提交回复
热议问题