Exemple #1
0
def play_video(video):
    VIDEO_PATH = Path(video)

    player = None
    try:
        arguments = "--no-osd -o alsa --aspect-mode fill"
        if DEV_MODE:
            arguments = arguments + " --win '0 0 400 300'"

        player = OMXPlayer(VIDEO_PATH, args=arguments)

        # App is real slow to boot and start playing video
        time.sleep(1)

        player.play()

    except SystemError:
        print "OMXPlayer failed to start, maybe"
        print "Sleeping for 60 seconds in case it didn't actually fail..."
        time.sleep(60)

    except OMXPlayerDeadError:
        print "OMXPlayer appeared to close, video likely ended!"

    except DBusException:
        print "OMXPlayer not replying, video likely ended!"

    finally:
        return player
    def play(self, audioID: str, saveID: str) -> NoReturn:
        """ 
			Play a pre-recorded response from the cache, and then copy and resave it with a
			current audio index number.
		"""

        AUDIO_PATH = Path("../data/cache/responses/" + audioID + ".wav")

        audiolen = TinyTag.get(
            AUDIO_PATH
        ).duration  # Get the duration of the recording of the reply

        try:
            player = OMXPlayer(AUDIO_PATH)  # Play the recording

            # Handle potential errors when the user hasn't set a speech pause amount.
            # In these cases, no pause
            pause = float(self.cfg.pause if (
                type(self.cfg.pause) is not None) else 0)
            sleep(
                audiolen + pause
            )  # Allow the audio to finish playing before quitting, and add a little leeway
        except Exception:
            raise AudioPlaybackError
        else:
            subprocess.call(
                f"cp ../data/cache/responses/{audioID}.wav ../data/cache/responses/{saveID}.wav",
                shell=True)
            pass
        finally:
            player.quit()  # Exit the player
Exemple #3
0
class Gameplay3(Result):
    t = 0.0

    def __init__(self):
        super(Gameplay3, self).__init__()
        self.image = Sprite(position=(0, 0),
                            image=load_image("images/things/intro.png"))
        self.next_state = "GAMEPLAY3a"

    def startup(self, persistent):
        self.rt = config.load("positions", "center", [[0, 0], [0, 0], [0, 0]])
        self.persist = persistent
        video = "images/things/intro.mp4"
        if OMXPlayer is not None and os.path.isfile(video):
            self.player = OMXPlayer(video, args=['--no-osd', '--loop'])
        else:
            self.player = None
        self.t = 0

    def update(self, dt):
        self.t += dt
        if self.t > 15000:
            self.done = True

    def draw(self, surface):
        self.image.draw(surface)

    def get_event(self, event):
        super(Gameplay3, self).get_event(event)
        if self.done and self.player is not None:
            self.player.quit()
            self.player = None
    def play(self, movie, loop=None, vol=0):
        """Play the provided movie file, optionally looping it repeatedly."""
        self.stop(3)  # Up to 3 second delay to let the old player stop.
        # Assemble list of arguments.
        #args = ['omxplayer']
        args = []
        args.extend(['-o', self._sound])  # Add sound arguments.
        args.extend(self._extra_args)  # Add extra arguments from config.
        if vol is not 0:
            args.extend(['--vol', str(vol)])
        if loop is None:
            loop = movie.repeats
        if loop <= -1:
            args.append('--loop')  # Add loop parameter if necessary.
        #if self._show_titles and movie.title:
        #    srt_path = os.path.join(self._get_temp_directory(), 'video_looper.srt')
        #    with open(srt_path, 'w') as f:
        #        f.write(self._subtitle_header)
        #        f.write(movie.title)
        #    args.extend(['--subtitles', srt_path])
        #args.append(movie.filename)       # Add movie file path.
        # Run omxplayer process and direct standard output to /dev/null.
        #self._process = subprocess.Popen(args,
        #                                 stdout=open(os.devnull, 'wb'),
        #                                 close_fds=True)


#        OMXPlayer('path.mp4', args='--no-osd --no-keys -b')
        self._player = OMXPlayer(movie.filename,
                                 dbus_name='org.mpris.MediaPlayer2.omxplayer1',
                                 args=args)
        self._player.stopEvent = self.player_stop
Exemple #5
0
    def __play(self):
        logging.info("Starting OMXPlayer for {} at {}".format(self.vid_data.id, self.start_time))

        args = ["-o", "local"]
        if self.start_time != 0:
            args += ["--pos", get_timestamp(self.start_time)]
        if Player.current_volume != 1 and Player.current_volume != 0:
            args += ["--vol", str(linear_to_mbels(Player.current_volume))]

        if Player.current_player is not None:
            Player.current_player.stop()
        Player.current_player = self

        Player.status = PlayerStatus.PLAYING
        self.omx = OMXPlayer(self.vid_data.url, args=args)
        self.omx.exitEvent += lambda p, code: self.stop()

        if self.done:
            self.omx.exitEvent += lambda p, code: self.done()

        self.start_timestamp = time.time() - self.start_time

        if Player.current_volume == 0:
            self.omx.mute()

        logging.info("OMXPlayer for {} has started".format(self.vid_data.id))
Exemple #6
0
    def loop(self):
        try:
            end_time = datetime.now() + timedelta(seconds=60)
            while (datetime.now() < end_time):
                self.data = self.audioinput()
                self.fft()
                if frequency_got == 1000 or frequency_got == -1000:
                    #print("got it")

                    player = OMXPlayer(
                        path +
                        "Hi, I have detected noise levels greater than the average value of 70 to 75 db. This is indicative of Cavitation, which could harm the equipment. I have raised an incident.mp3"
                    )
                    player.set_volume(1)
                    time.sleep(5)

                    break
                #self.graphplot()
            #self.stream.stop_stream()
            #self.stream.close()

        except KeyboardInterrupt:
            self.pa.close()

        print("End...")
Exemple #7
0
class ToonPlayer(object):
    """omxplayer-wrapper throws an exception if it can't find an
    active dbus listing.  This isn't really what I want so I'll
    fix that with my own class and some composition.

    -b is here to black out the background terminal.
    """
    def __init__(self, source):
        self._player = OMXPlayer(source, '-b')
        sleep(2)

    def play(self, source):
        self._player.load(source)

    def seek(self, time):
        self._player.seek(time)

    def active(self):
        try:
            if self._player.is_playing():
                return True
            else:
                return False
        except Exception as ex:
            return False
Exemple #8
0
 def mirror(self):
     self.player = OMXPlayer("udp://0.0.0.0:8090?listen",
                             args=[
                                 '-o', 'hdmi', '--lavfdopts',
                                 'probesize:8000', '--timeout', '0',
                                 '--threshold', '0'
                             ])
Exemple #9
0
    def run(self):
        """Thread target."""
        while not self.stopped:
            current_clip = Video.get_next()
            if current_clip is None:
                self.logger.debug("No clips in database. Waiting...")
                sleep(5)
            else:
                self.logger.debug(
                    "Starting video player with clip [{}]".format(
                        current_clip["filename"][:6]))

                full_path = self.filepath(current_clip)

                if machine() == "armv7l":
                    player_args = [
                        '--blank', '-o', 'hdmi', '--loop', '--no-osd',
                        '--aspect-mode', 'fill', '--win', "'0, 0, 810, 540'"
                    ]
                else:
                    player_args = ['-b', '--loop']

                if self.player is None:
                    self.player = OMXPlayer(full_path, player_args)
                else:
                    self.player.load(full_path, player_args)
                    self.player.play()

                sleep(5)
                self.player.pause()
        self.logger.debug("Exit video player")
Exemple #10
0
def show_video(video, loop=True):
    global omx
    if os.path.exists(video):
        show_icon('')
        if platform.system() != 'Windows':
            if (omx != None):
                log.info('Starting video: ' + video)
                try:
                    omx.load(video)
                except OMXPlayerDeadError:
                    log.info('OMX was dead, creating new player for video: ' +
                             video)
                    omx = OMXPlayer(video,
                                    args=[
                                        '--loop', '--no-osd', '--layer', '-1',
                                        '--no-keys', '-b'
                                    ])
            else:
                log.info('Starting OMX with video: ' + video)
                omx = OMXPlayer(
                    video,
                    args=(['--loop'] if loop else []) +
                    ['--no-osd', '--layer', '-1', '--no-keys', '-b'])
    else:
        stop_video()
        show_icon(MISSING_FILE_ICON)
        log.warning('Video not found: ' + video)
Exemple #11
0
def sendSteps(songNum):
    # pulse reset signal before sending over steps
    resetLed.on()
    resetLed.off()
    # calculate sleep amount outside loop
    sleepAmount = 30 / OneThingBPM
    # asynchronously play audio
    if songNum == 0:
        player = OMXPlayer(Path(OneThingMP3Path))
    else:
        player = OMXPlayer(Path(TheNightsMusic))
    # send over steps
    if songNum == 0:
        chart = OneThingSteps
    else:
        chart = TheNightsSteps
    for step in chart:
        start = time()
        stepLeds.value = tuple(step)
        # pulse BPM clock
        bpmClockLed.on()
        end = time()
        # sleep appropriately
        sleep(sleepAmount - (end - start))
        start = time()
        bpmClockLed.off()
        end = time()
        sleep(sleepAmount - (end - start))
    # make sure steps don't persist on led matrix
    stepLeds.value = tuple([0] * 4)
Exemple #12
0
def play():
    global player

    if player:
        player.quit()

    filename = get_top() if mode == TOP20_MODE else get_random()
    episode = filename.replace('.mp4', '').replace('.mkv', '').split(' - ')
    color = TERM_COLORS.RANDOM
    isTop = ''

    # render top place if any
    if episode[0] in top_episode_list:
        isTop = 'Top# ' + str(20 - top_episode_list.index(episode[0])) + ' : '
        color = TERM_COLORS.TOP20

    print("\n\n\n Playing...")
    print(color + (Figlet(font=FONTS.SEASON, width=LINE_LENGTH)
                   ).renderText(isTop + 's' + episode[0].replace('x', ' e')) +
          TERM_COLORS.ENDC + "\r")

    print(TERM_COLORS.TITLE +
          (Figlet(font=FONTS.TITLE, width=LINE_LENGTH)
           ).renderText(episode[1].replace('ü', 'u').replace('ú', 'u').replace(
               'é', 'e').replace('á', 'a').replace('í', 'i').replace(
                   'ó', 'o').replace('ñ', 'n')) + TERM_COLORS.ENDC)

    player = OMXPlayer(Path(DIRECTORY + filename))
    player.set_aspect_mode('fill')
Exemple #13
0
class Radio:
    def __init__(self):
        self.stations = [('KPOA',
                          'https://16693.live.streamtheworld.com/KPOAFM.mp3 '),
                         ('KAZU', 'https://icecastle.csumb.edu/live128'),
                         ('KZSC', 'http://streaming.kzsc.org:8000/kzschigh')]
        self.station_index = 0
        self.play = False
        self.player = False

    def __str__(self):
        state = ""
        if self.play:
            state = "on"
        else:
            state = "off"
        return "{} -- {}".format(self.stations[self.station_index][0], state)

    def get_stations(self):
        return self.stations

    def current(self):
        return self.stations[self.station_index]

    def next(self):
        if self.play:
            self.off()
        self.station_index = self.station_index + 1
        if self.station_index > len(self.stations) - 1:
            self.station_index = 0
        return self.stations[self.station_index]

    def previous(self):
        if self.play:
            self.off()
        self.station_index = self.station_index - 1
        if self.station_index < 0:
            self.station_index = len(self.stations) - 1
        return self.stations[self.station_index]

    def toggle(self):
        self.play = not self.play
        if not self.play:
            self.off()
        else:
            self.on()
        return self.play

    def on(self):
        self.play = True
        print("playing {}".format(self.stations[self.station_index][0]))
        self.player = OMXPlayer(self.stations[self.station_index][1])
        return self.play

    def off(self):
        self.play = False
        if self.player:
            print("stopping {}".format(self.stations[self.station_index][0]))
            self.player.quit()
        return self.play
 def play_vid(self):
     self.logging.debug("Play button func")
     self.logging.debug("Playing: {0} Paused: {1}".format(
         self.playing, self.paused))
     self.logging.debug("Current subreddit index: %d" %
                        self.subreddits[self.curr_subreddit][1])
     self.logging.debug("Current video URL: %s" % self.subreddits[
         self.curr_subreddit][2][self.subreddits[self.curr_subreddit][1]])
     if not self.playing:
         if self.paused:
             self.player = OMXPlayer(
                 self.subreddits[self.curr_subreddit][2][self.subreddits[
                     self.curr_subreddit][1]],
                 args=[
                     '--aspect-mode', 'Letterbox', '--pos', self.position
                 ])
             self.paused = False
         else:
             self.player = OMXPlayer(
                 self.subreddits[self.curr_subreddit][2][self.subreddits[
                     self.curr_subreddit][1]],
                 args=['--aspect-mode', 'Letterbox'])
         self.alive = True
         self.player.exitEvent += lambda x, y: self.exit_event_func()
         self.root.update()
         self.playing = True
     else:
         self.paused = True
         self.playing = False
         self.position = self.player.position()
         self.player.stop()
Exemple #15
0
def musicactions():
    # if(request.method == 'GET'):
    s = request.query_string
    a = dict(item.split("=") for item in s.split("&"))
    action = a["action"]
    if (action == "stop"):
        global player
        global q
        if (q != True):
            print("QUIT")
            player.quit()
            q = True
    elif (action == "play"):
        global player
        q = False
        player = OMXPlayer("file.m4a")
        print(player)
    elif (action == "setvolume"):
        volume = float(a["volume"])
        try:
            player.unmute()
            if (volume > 50):
                player.set_volume(450 * volume / 100)
            elif (volume < 50 and volume > 0):
                player.set_volume(-100 / (volume / 100))
            elif (volume == 0):
                player.mute()
        except:  #Exception as OMXPlayerDeadError:
            print("No Player")
    return "true"
Exemple #16
0
class Gameplay3b(Result):
    animations = []
    animation = None
    invert = 0

    def __init__(self):
        super(Gameplay3b, self).__init__()
        self.images = [
            Sprite(position=(0, 0),
                   image=load_image("images/things/" + x + ".png"))
            for x in things
        ]
        self.next_state = "GAMEPLAY3a"
        #for i, thing in enumerate(things):
        #    try:
        #        anim = AnimatedSprite(position=pos[i], images=load_images("images/things/"+thing.lower()+""))
        #        self.animations.append(anim)
        #    except Exception as e:
        #        self.animations.append(None)
        #        print(e)

    def startup(self, persistent):
        self.rt = config.load("positions", "center", [[0, 0], [0, 0], [0, 0]])
        self.persist = persistent
        i = self.persist["choice"] if "choice" in self.persist else 0
        self.image = self.images[i]
        # self.invert = things[i] in ["LUMI", "MURU"]
        video = "images/things/" + things[i].lower() + ".mp4"
        if OMXPlayer is not None and os.path.isfile(video):
            self.player = OMXPlayer(video, args=['--no-osd', '--loop'])
        else:
            self.player = None

        #try:
        #    self.animation = None
        #    gc.collect()
        #    self.animation = AnimatedSprite(position=pos[i], images=load_images("images/things/" + things[i].lower() + "", False))
        #except Exception as e:
        #    self.animation = None
        #    print(e)

    def get_event(self, event):
        super(Gameplay3b, self).get_event(event)
        if self.done and self.player is not None:
            self.player.quit()
            self.player = None

    def draw(self, surface):
        if self.invert:
            if self.animation is not None:
                self.animation.draw(surface)
                self.image.draw(surface)
        else:
            self.image.draw(surface)
            if self.animation is not None:
                self.animation.draw(surface)

    def update(self, dt):
        if self.animation is not None:
            self.animation.update(dt)
Exemple #17
0
 def start_stream(self, stream_id):
     videos = json.load(open('videos.json', 'r'))
     video = next((item for item in videos if item["id"] == stream_id),
                  None)
     url = video.uri
     self.player1 = OMXPlayer(url,
                              args='--win 0,0,1920,1080',
                              dbus_name='orb.mpris.MediaPlayer2.omxplayer1')
Exemple #18
0
 def vid(self):
     print("video clicked, ID: " + self.ID)
     if os.path.isfile('/home/pi/proto/Twin/vid/' + self.ID + '.mp4'):
         player = OMXPlayer('/home/pi/proto/Twin/vid/' + self.ID + '.mp4')
         sleep(31)
         player.quit()
     else:
         print("동영상을 제공하지 않는 광고입니다.")
Exemple #19
0
 def vid(self):
     print("video clicked, ID: " + self.ID)
     if os.path.isfile('/home/pi/proto/Twin/vid/' + self.ID + '.mp4'):
         player = OMXPlayer('/home/pi/proto/Twin/vid/' + self.ID + '.mp4')
         sleep(31)
         player.quit()
     else:
         self.showMessageBox()
Exemple #20
0
 def play_pause(self):
     if self.omx:
         self.omx.play_pause()
     else:
         current_music_queue = list(self.current_music.queue)
         current_music = current_music_queue[0] if current_music_queue else None
         if current_music:
             self.omx = OMXPlayer(current_music['url'])
Exemple #21
0
 def patch_and_run_omxplayer_url(self, Connection=Mock(), active=False):
     bus_address_finder = Mock()
     bus_address_finder.get_address.return_val = "example_bus_address"
     self.player = OMXPlayer(self.TEST_URL,
                             bus_address_finder=bus_address_finder,
                             Connection=Connection)
     if active:
         self.player._process.poll = Mock(return_value=None)
Exemple #22
0
 def __init__(self, player_id, video_path):
     self.player_id = player_id
     self.video_path = video_path
     self.player = OMXPlayer(video_path,
                             args=['--loop'],
                             dbus_name="org.mpris.MediaPlayer2.player" +
                             player_id)
     sleep(2)
Exemple #23
0
 def threeD(self):
     print("3D clicked, ID: " + self.ID)
     if os.path.isfile('/home/pi/proto/Twin/3D/' + self.ID + '.mp4'):
         player = OMXPlayer('/home/pi/proto/Twin/3D/' + self.ID + '.mp4')
         sleep(31)
         player.quit()
     else:
         print("3D 모델을 제공하지 않는 광고입니다.")
Exemple #24
0
 def threeD(self):
     print("3D clicked, ID: " + self.currAD)
     if os.path.isfile('/home/pi/proto/Twin/3D/' + self.currAD + '.mp4'):
         player = OMXPlayer('/home/pi/proto/Twin/3D/' + self.currAD +
                            '.mp4')
         sleep(31)
         player.quit()
     else:
         self.showMessageBox('3D모델')
Exemple #25
0
 def startup(self, persistent):
     self.rt = config.load("positions", "center", [[0, 0], [0, 0], [0, 0]])
     self.persist = persistent
     video = "images/things/intro.mp4"
     if OMXPlayer is not None and os.path.isfile(video):
         self.player = OMXPlayer(video, args=['--no-osd', '--loop'])
     else:
         self.player = None
     self.t = 0
Exemple #26
0
 def play(self):
     self.player = OMXPlayer(self.path, args="-o local")
     self.player.exitEvent = self.exitEvent
     self.player.stopEvent = self.stopEvent
     while not self.finished:
         sleep(0.5)
         if self.syncCallback and not self.finished:
             self.syncCallback(self.player.position())
     self.player.quit()
Exemple #27
0
 def playFile(self, fileName):
     if self.player == None:
         self.player = OMXPlayer(fileName)
         self.player.set_volume(self.volume)
         self.player.exitEvent += lambda _, exit_code: self.playerExit(
             exit_code)
     else:
         self.player.load(fileName)
     self.playing = True
Exemple #28
0
 def setup_player_two(self):
     self.player2 = OMXPlayer(self.baseUrl +
                              self.video_playlist[self.nextIndex],
                              args='--win 0,0,1920,1080 --layer 1',
                              dbus_name='orb.mpris.MediaPlayer2.omxplayer2',
                              pause=True)
     self.player2.playEvent += lambda _: self.player_log.info(" 2 Play")
     self.player2.pauseEvent += lambda _: self.player_log.info("2 Pause")
     self.player2.stopEvent += lambda _: self.player_log.info("2 Stop")
Exemple #29
0
 def youtube(self):
     proc = subprocess.Popen(['youtube-dl', '-g', '-f', 'mp4', self.url],
                             stdout=subprocess.PIPE)
     url = proc.stdout.read()
     if url.decode("utf-8") == '':
         return False
     self.player = OMXPlayer(url.decode("utf-8", "strict")[:-1],
                             args=['-o', 'hdmi'])
     return True
Exemple #30
0
 def play(self):
     VIDEO_PATH = Path("videos/" + self.video_path)
     print(VIDEO_PATH)
     self.player = OMXPlayer(VIDEO_PATH,
                             args=['-o', 'alsa', '--layer', '100000'])
     self.player.set_video_pos(0, 0, 800, 480)
     self.set_slider()
     self.change_size()
     Clock.schedule_interval(self.set_slider, 3)
     Clock.schedule_interval(self.set_play_pause_bttn, 1)
def init_player_obj():
    # Initialize the OMXPlayer and sleep to load in video
    prod_args = ['--no-osd', '--vol', str(VIDEO_VOLUME), '-o', VIDEO_AUDIO_SOURCE]
    dev_args = ['--win', '0,40,600,400', '--no-osd', '--vol', str(VIDEO_VOLUME), '-o', VIDEO_AUDIO_SOURCE]
    player = OMXPlayer(VIDEO_PATH, dev_args, pause=True)
    player.pause()
    sleep(5)
    vid_tree_root = create_beyblade_vid_tree()
    player_obj = VidPlayer(player, vid_tree_root)
    print("Player ready")
    return player_obj
def playMedia(path="../tests/media/test_media_1.mp4", duration=0, position=0):
    player = OMXPlayer(path, args=["--no-osd"])
    player.set_aspect_mode("fill")
    if position > 0:
            player.set_position(position)
    #player.duration() # this only works if this line is here
    if duration == 0:
            duration = player.duration() - position
    player.play()
    time.sleep(duration)
    player.quit()
 def patch_and_run_omxplayer_url(self, Connection=Mock(), active=False):
     bus_address_finder = Mock()
     bus_address_finder.get_address.return_val = "example_bus_address"
     self.player = OMXPlayer(self.TEST_URL,
                             bus_address_finder=bus_address_finder,
                             Connection=Connection)
     if active:
         self.player._process.poll = Mock(return_value=None)
    def test_init_pause(self, *args):
        with patch.object(OMXPlayer, 'pause', return_value=None) as pause_method:
            # self.patch_and_run_omxplayer(pause=False)
            bus_address_finder = Mock()
            bus_address_finder.get_address.return_val = "example_bus_address"
            self.player = OMXPlayer(self.TEST_FILE_NAME,
                                bus_address_finder=bus_address_finder,
                                Connection=Mock(),
                                pause=True)

            self.assertEqual(pause_method.call_count, 1)
                print('positioning to 2 %s (%s)' % (keyname, updown))
            else:
                print('player cannot seek %s (%s)' % (keyname, updown))
        elif keyname == b'KEY_4':
            if player.can_seek():
                player.set_position(4)
                print('positioning to 4 %s (%s)' % (keyname, updown))
            else:
                print('player cannot seek %s (%s)' % (keyname, updown))
        elif keyname == b'KEY_9' and updown == b'00':
            print('calling aplay with audio path %s' % AUDIO_CHEER_PATH)
            subprocess.Popen(['aplay', AUDIO_CHEER_PATH])

    print('goodbye')


if __name__ == '__main__':

    init_irw()

    # Initialize the OMXPlayer and sleep to load in video
    player = OMXPlayer(VIDEO_PATH, args=['--no-osd', '--vol', str(VIDEO_VOLUME), '-o', VIDEO_AUDIO_SOURCE], pause=True)
    player.pause()
    sleep(3)

    try:
        run_player(player)
    except Exception as e:
        player.quit()
        raise e
Exemple #36
0
#!/usr/bin/env python3

from omxplayer.player import OMXPlayer
from pathlib import Path
from time import sleep

VIDEO_PATH_OPENING = Path("./assets/opening.mp4")
VIDEO_PATH_BATTLE = Path("./assets/battle-test.mp4")

player_opening = OMXPlayer(VIDEO_PATH_OPENING, args=['--no-osd'], pause=True)

#player_battle = OMXPlayer(VIDEO_PATH_BATTLE)
#player_battle.pause()

sleep(5)

player_opening.play()

sleep(3)

player_opening.stop()
player_opening.quit()
print("quit opening player")

#sleep(3)

#print("creating new player instance for the battle")

#player_battle = OMXPlayer(VIDEO_PATH_BATTLE)

#sleep(5)
def play_film(filename="demo.mp4", duration=0, position=0):
    debug("\nfilename:", filename)
    debug("  position:", position)
    debug("  duration:", duration)
    trim_from_end = 0.5
    #trim_from_end = 0
    player = OMXPlayer(filename)
    player.set_position(0.0)
    debug("  pre-play pos:", player.position())
    player.play()
    # check and set position
    full_length = player.duration()
    # if the position is imposible, set it to 0
    if position <= 0 or position > full_length:
        position = 0.0
    player.set_position(position)
    # check and set duration
    length_to_end = player.duration()
    # if duration is imposible, set it to the length_to_end
    if duration == 0 or duration > length_to_end:
        wait = length_to_end - trim_from_end
    else:
        wait = duration
    if wait < 0:
        wait = 0
    debug("  full length: ", full_length)
    debug("  length to end: ", length_to_end)
    debug("  wait: ", wait)
    sleep(wait)
    debug("  post sleep pos:", player.position())
    player.pause()
    player.quit()
    debug("  post pause pos:", player.position())
    return True
class OMXPlayerTests(unittest.TestCase):
    TEST_FILE_NAME = "./test.mp4"
    TEST_URL = "rtmp://192.168.0.1/live/mystream"

    def test_opens_file_in_omxplayer(self, popen, *args):
        self.patch_and_run_omxplayer()
        devnull = MOCK_OPEN()
        popen.assert_called_once_with(
            ['omxplayer', './test.mp4'],
            preexec_fn=os.setsid,
            stdin=devnull,
            stdout=devnull)

    @patch('time.sleep')
    def test_tries_to_open_dbus_again_if_it_cant_connect(self, *args):
        # TODO: Shouldn't this be DBusConnectionError not SystemError
        with self.assertRaises(SystemError):
            dbus_connection = Mock(side_effect=DBusConnectionError)
            self.patch_and_run_omxplayer(Connection=dbus_connection)
            self.assertEqual(50, self.player.tries)

    @parameterized.expand([
        ['can_quit', 'CanQuit', [], []],
        ['can_set_fullscreen', 'CanSetFullscreen', [], []],
        ['identity', 'Identity', [], []]
    ])
    def test_root_interface_properties(self, popen, sleep, isfile, killpg, atexit, command_name,
                                       property_name, command_args, expected_dbus_call_args):
        self.patch_and_run_omxplayer()
        self.player._root_interface.dbus_interface = "org.mpris.MediaPlayer2"
        interface = self.player._properties_interface
        interface.reset_mock()

        self.patch_interface_and_run_command(command_name, command_args)

        expected_call = call.Get("org.mpris.MediaPlayer2", property_name, *expected_dbus_call_args)
        interface.assert_has_calls([expected_call])

    @parameterized.expand([
        ['pause', 'Pause', [], []],
        ['stop', 'Stop', [], []],
        ['seek', 'Seek', [100], [dbus.Int64(100 * 1e6)]],
        ['set_position', 'SetPosition', [1], [dbus.ObjectPath("/not/used"), dbus.Int64(1000000)]],
        ['list_subtitles', 'ListSubtitles', [], []],
        ['mute', 'Mute', [], []],
        ['unmute', 'Unmute', [], []],
        ['action', 'Action', ['p'], ['p']]
    ])
    def test_player_interface_commands(self, popen, sleep, isfile, killpg, atexit, command_name,
                                       interface_command_name, command_args, expected_dbus_call_args):
        self.patch_and_run_omxplayer()
        self.player._player_interface.dbus_interface = "org.mpris.MediaPlayer2"
        interface = self.player._player_interface
        interface.reset_mock()

        self.patch_interface_and_run_command(command_name, command_args)

        expected_call = getattr(call, interface_command_name)(*expected_dbus_call_args)
        interface.assert_has_calls([expected_call])

    @parameterized.expand([
        ['can_play', 'CanPlay', True, dbus.Boolean(True)],
        ['can_seek', 'CanSeek', False, dbus.Boolean(False)],
        ['can_control', 'CanControl', True, dbus.Boolean(True)],
        ['playback_status', 'PlaybackStatus', "playing", dbus.String("playing")],
        ['position', 'Position', 1.2, dbus.Int64(1.2 * 1000 * 1000)],
        ['duration', 'Duration', 10.1, dbus.Int64(10.1 * 1000 * 1000)],
        ['volume', 'Volume', 10, dbus.Int64(10)],
        ['minimum_rate', 'MinimumRate', 0.1, dbus.Double(0.1)],
        ['maximum_rate', 'MaximumRate', 4.0, dbus.Double(4.0)],
    ])
    def test_player_interface_properties(self, popen, sleep, isfile, killpg, atexit,
                        command_name, property_name, expected_result, property_result):
        interface_address = "org.mpris.MediaPlayer2"
        self.patch_and_run_omxplayer()
        self.player._root_interface.dbus_interface = interface_address
        interface = self.player._properties_interface
        interface.reset_mock()
        mock = interface.Get
        mock.configure_mock(return_value=property_result)

        result = self.patch_interface_and_run_command(command_name, [])

        interface.assert_has_calls([(call.Get(interface_address, property_name))])
        self.assertEqual(expected_result, result)

    def test_quitting(self, popen, sleep, isfile, killpg, *args):
        omxplayer_process = Mock()
        popen.return_value = omxplayer_process
        self.patch_and_run_omxplayer()
        with patch('os.getpgid', Mock(return_value=omxplayer_process.pid)):
            self.player.quit()
            killpg.assert_called_once_with(omxplayer_process.pid, signal.SIGTERM)

    def test_quitting_waits_for_omxplayer_to_die(self, popen, *args):
        omxplayer_process = Mock()
        popen.return_value = omxplayer_process
        self.patch_and_run_omxplayer()
        with patch('os.getpgid'):
            self.player.quit()
            omxplayer_process.wait.assert_has_calls([call()])

    def test_check_process_still_exists_before_dbus_call(self, *args):
        self.patch_and_run_omxplayer()
        self.player._process = process = Mock(return_value=None)
        process.poll.return_value = None

        self.player.can_quit()

        process.poll.assert_called_once_with()

    def test_stop_event(self, *args):
        self.patch_and_run_omxplayer(active=True)
        callback = Mock()
        self.player.stopEvent += callback

        self.player.stop()

        callback.assert_called_once_with(self.player)

    def test_play_event(self, *args):
        self.patch_and_run_omxplayer(active=True)
        callback = Mock()
        self.player.playEvent += callback

        with patch.object(self.player, 'is_playing', return_value=False):
            self.player.play()

            callback.assert_called_once_with(self.player)

    def test_pause_event(self, *args):
        self.patch_and_run_omxplayer(active=True)
        callback = Mock()
        self.player.pauseEvent += callback

        with patch.object(self.player, 'is_playing', return_value=True):
            self.player.pause()

            callback.assert_called_once_with(self.player)

    def test_play_event_by_play_pause(self, *args):
        self.patch_and_run_omxplayer(active=True)
        callback = Mock()
        self.player.playEvent += callback

        with patch.object(self.player, 'is_playing', return_value=False):
            self.player.pause()

            # play
            self.player.play_pause()

            callback.assert_called_once_with(self.player)

    def test_pause_event_by_play_pause(self, *args):
        self.patch_and_run_omxplayer(active=True)
        callback = Mock()
        self.player.pauseEvent += callback

        with patch.object(self.player, 'is_playing', return_value=True):
            self.player.play()

            # pause
            self.player.play_pause()

            callback.assert_called_once_with(self.player)

    def test_seek_event(self, *args):
        self.patch_and_run_omxplayer(active=True)
        callback = Mock()
        self.player.seekEvent += callback

        self.player.seek(3.4)

        callback.assert_called_once_with(self.player, 3.4)

    def test_position_event(self, *args):
        self.patch_and_run_omxplayer(active=True)
        callback = Mock()
        self.player.positionEvent += callback

        self.player.set_position(5.01)

        callback.assert_called_once_with(self.player, 5.01)

    def patch_interface_and_run_command(self, command_name, command_args):
        self.player._process.poll = Mock(return_value=None)
        result = getattr(self.player, command_name)(*command_args)
        return result

    # Must have the prefix 'patch' for the decorators to take effect
    def patch_and_run_omxplayer(self, Connection=Mock(), active=False):
        bus_address_finder = Mock()
        bus_address_finder.get_address.return_val = "example_bus_address"
        self.player = OMXPlayer(self.TEST_FILE_NAME,
                                bus_address_finder=bus_address_finder,
                                Connection=Connection)
        if active:
            self.player._process.poll = Mock(return_value=None)

    def patch_and_run_omxplayer_url(self, Connection=Mock(), active=False):
        bus_address_finder = Mock()
        bus_address_finder.get_address.return_val = "example_bus_address"
        self.player = OMXPlayer(self.TEST_URL,
                                bus_address_finder=bus_address_finder,
                                Connection=Connection)
        if active:
            self.player._process.poll = Mock(return_value=None)

    def test_load(self, popen, sleep, isfile, killpg, *args):
        omxplayer_process = Mock()
        popen.return_value = omxplayer_process
        with patch('os.getpgid', Mock(return_value=omxplayer_process.pid)):
            self.patch_and_run_omxplayer(active=True)
            # initial load
            self.assertEqual(self.player.get_filename(), './test.mp4')
            killpg.assert_not_called()
            popen.assert_called_once_with(['omxplayer', './test.mp4'],
                                        preexec_fn=os.setsid,
                                        stdin=MOCK_OPEN(),
                                        stdout=MOCK_OPEN())
            # load new video in same OMXPlayer instance
            self.player.load('./test2.mp4')
            # verify new video is registered in OMXPlayer
            self.assertEqual(self.player.get_filename(), './test2.mp4')
            # verify omxplayer process for previous video was killed
            killpg.assert_called_once_with(omxplayer_process.pid, signal.SIGTERM)
            # verify a new process was started for the second time
            self.assertEqual(popen.call_count, 2)

    def test_init_without_pause(self, *args):
        with patch.object(OMXPlayer, 'pause', return_value=None) as pause_method:
            self.patch_and_run_omxplayer()
            self.assertEqual(pause_method.call_count, 0)

    def test_init_pause(self, *args):
        with patch.object(OMXPlayer, 'pause', return_value=None) as pause_method:
            # self.patch_and_run_omxplayer(pause=False)
            bus_address_finder = Mock()
            bus_address_finder.get_address.return_val = "example_bus_address"
            self.player = OMXPlayer(self.TEST_FILE_NAME,
                                bus_address_finder=bus_address_finder,
                                Connection=Mock(),
                                pause=True)

            self.assertEqual(pause_method.call_count, 1)

    def test_load_and_pause(self, *args):
        with patch.object(OMXPlayer, 'pause', return_value=None) as pause_method:
            self.patch_and_run_omxplayer()
            self.player.load('./test2.mp4', pause=True)
            self.assertEqual(pause_method.call_count, 1)

    def test_load_without_pause(self, *args):
        with patch.object(OMXPlayer, 'pause', return_value=None) as pause_method:
            self.patch_and_run_omxplayer()
            self.player.load('./test2.mp4')
            self.assertEqual(pause_method.call_count, 0)

    def test_register_quit_handler_atexit(self, popen, sleep, isfile, killpg, atexit):
        self.patch_and_run_omxplayer()
        atexit.assert_called_once_with(self.player.quit)
#!/usr/bin/env python3

from omxplayer.player import OMXPlayer
from pathlib import Path
from time import sleep
import logging
logging.basicConfig(level=logging.INFO)


VIDEO_1_PATH = "../tests/media/test_media_1.mp4"
player_log = logging.getLogger("Player 1")

player = OMXPlayer(VIDEO_1_PATH, 
        dbus_name='org.mpris.MediaPlayer2.omxplayer1')
player.playEvent += lambda _: player_log.info("Play")
player.pauseEvent += lambda _: player_log.info("Pause")
player.stopEvent += lambda _: player_log.info("Stop")

# it takes about this long for omxplayer to warm up and start displaying a picture on a rpi3
sleep(2.5)

player.set_position(5)
player.pause()


sleep(2)

player.set_aspect_mode('stretch')
player.set_video_pos(0, 0, 200, 200)
player.play()
Exemple #40
0
	def __init__(self):
		#loading settings from setup.config
		settings = sl_settings.Settings()
		if not settings.load():
			error(1)

		ip_setup = dynamic_ip()
		ip_setup.set(settings.get("ip_address"))
	
		plr = OMXPlayer(settings.get("file_name"),["--blank","--no-osd"])

		if settings.get("ismaster") == "True":
			if ip_setup.waitForConnections(settings.get("num_clients")):
				ip_setup.sendStartSignal()
		else:
			ip_setup.connectToServer()
			ip_setup.waitForStartSignal()
			print "this function is not ready yet"
			### TODO: error check 
		#loop_time = plr.duration() - float(settings.get("load_time"))
		plr.play()
	
		while True:
			try:
				if settings.get("ismaster") == "False":
					ip_setup.waitForStartSignal()
					plr.set_position(0)
				elif settings.get("ismaster") == "True":
					sleep(plr.duration() - 1.0)
					#sleep(6)
					ip_setup.sendStartSignal()
					plr.set_position(0)
			except KeyboardInterrupt:
				print "interrupted!"
				ip_setup.closeConnection()
				ip_setup.setOldIp()
				plr.stop()
				plr.quit()
				break
		#plr.stop()

		ip_setup.setOldIp()
#!/usr/bin/env python3

from omxplayer.player import OMXPlayer
from pathlib import Path
from time import sleep

VIDEO_PATH = Path("../tests/media/test_media_1.mp4")

player = OMXPlayer(VIDEO_PATH)

sleep(5)

player.quit()