Exemplo n.º 1
0
class Video_Player:
    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)

    #

    def load(self, video_path):
        self.player.hide_video()
        self.video_path = video_path
        self.player.load(video_path)

    def play(self):
        self.player.play()
        self.player.show_video()

    def pause(self):
        self.player.hide_video()
        self.player.pause()

    def stop(self):
        self.player.stop()
Exemplo n.º 2
0
def single_video_player_looper(video_clip_path, sleep_minutes, test_mode):
    """
    Loops a single video.

    Arguments
        video_clip_path     string
                            The path of the video clip being played.

        sleep_minutes       integer or float
                            Length of time to pause between loops.

        test_mode           boolean
                            True of False. If test_mode is True, clip is not
                            played in full screen mode.
    """

    test_mode_length = "720"
    test_mode_width = "360"
    play_message = "{} - Playing {}".format(current_time(), video_clip_path)
    if test_mode is True:
        player = OMXPlayer(video_clip_path,
                           args=[
                               "--no-osd", "--loop", "--win",
                               "0, 0, {0}, {1}".format(test_mode_length,
                                                       test_mode_width)
                           ])
        play_message = "{} in test mode".format(play_message)
    else:
        player = OMXPlayer(video_clip_path,
                           args=[
                               "--no-osd", "--loop", "--orientation", "180",
                               "--aspect-mode", "fill"
                           ])

    print(play_message)
    print("{} - {} minute(s) pause between each play".format(
        current_time(), sleep_minutes))

    try:
        player.pause()

        while True:
            print(play_message)
            player.play()
            sleep(player.duration())
            player.pause()
            player.set_position(0.0)
            if sleep_minutes > 0:
                if sleep_minutes < 1:
                    sleep_message = "{} seconds".format(
                        int(60.0 * sleep_minutes))
                else:
                    sleep_message = "{} minute(s)".format(sleep_minutes)
                print("{} - Sleeping {} before starting again".format(
                    current_time(), sleep_message))
                sleep(60 * sleep_minutes)
    except KeyboardInterrupt:
        print("{} - Exiting".format(current_time()))
        player.quit()
        sys.exit()
Exemplo n.º 3
0
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
Exemplo n.º 4
0
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
Exemplo n.º 5
0
    def playerFactory(filename, logger):
        '''
        Creates an instance of OMXPlayer the starting state
        we desire.

        If filename does not exist (or is None), generates a Mock devices
        with equivalent functionality (but no media output)
        '''

        if filename is not None and not os.path.isfile(filename):
            logger.warning("Media file: {} DOES NOT EXIST".format(filename))
            filename = None  # force try to fail quickly below

        try:
            player = OMXPlayer(filename,
                               dbus_name='org.mpris.MediaPlayer2.omxplayer1',
                               args=['-b', '-o', 'both'])
        except Exception as e:
            player = omxPlayerMock(filename)

        player.playEvent += lambda _: logger.debug("Play")
        player.pauseEvent += lambda _: logger.debug("Pause")
        player.stopEvent += lambda _: logger.debug("Stop")

        while True:
            try:
                player.hide_video()
                player.pause()
                break
            except Exception as e:
                logger.exception("Exception in playerFactory")
                sys.exit(1)
        return player
Exemplo n.º 6
0
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
Exemplo n.º 7
0
    def run(self, filename):
        global omxplayer

        gpio_control = GPIOControl()
        return_code = 0  # OK

        try:
            omxplayer = OMXPlayer(filename, OMXPLAYER_ARGS, None, None, True)
            omxplayer.pause()

            print 'Video player is armed!'
            print 'Video duration = ' + str(omxplayer.duration())

            #while(gpio_control.motion_detected()):
            #	continue;

            gpio_control.start()

            #loop_num = int(omxplayer.duration() / duration_sect)

            i = duration_sect
            last_sect = False

            while True:
                status = 0

                while status != 1:
                    pos = omxplayer.position()
                    #print str(pos)
                    if pos + 0.01 >= i:
                        if last_sect:
                            omxplayer.set_position(0)
                            last_sect = False
                            i = 0
                        status = 1
                    continue
                if gpio_control.motion_detected() == 0:
                    gpio_control.turn_off_relay()
                    omxplayer.pause()

                i += duration_sect
                if i + duration_sect >= omxplayer.duration():
                    last_sect = True

        except IOError as e:
            return_code = -1

        except KeyboardInterrupt:
            print 'KeyboardInterrupt'
            omxplayer.quit()

        print('EXIT')
        GPIO.cleanup()
        return return_code
Exemplo n.º 8
0
def play_video():
    player = OMXPlayer('video.mp4',
                       dbus_name='org.mpris.MediaPlayer2.omxplayer1',
                       args=['--loop', '--no-osd'])
    sleep(2.5)
    player.set_position(5)
    player.pause()
    sleep(2)
    player.set_aspect_mode('stretch')
    #player.set_fullscreen()
    # player.set_video_pos(0, 0, 200, 200)
    player.play()
    return player
Exemplo n.º 9
0
    def initPlayer(self, video, dbusName, log):

        player = OMXPlayer(video.path, dbus_name=dbusName, args=['--loop'])

        player.hide_video()
        player.pause()
        player.set_position(video.start)
        player.set_volume(video.volume)
        player.set_aspect_mode(video.aspect)

        player.active = False

        return player
Exemplo n.º 10
0
class Player:
    def __init__(self, url):
        self.url = url
        self.player = None
        self.state = True
        self.playlist = False
        self._play = True

    def start(self):
        if isinstance(self.url, string_types):
            cmd = 'youtube-dl -g -f best {0}'.format(self.url)
            yt_dl = subprocess.Popen(cmd,
                                     shell=True,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
            (url, err) = yt_dl.communicate()
            if yt_dl.returncode != 0:
                sys.stderr.write(err)
                print('error')
            yurl = url.decode('UTF-8').strip()
            self.player = OMXPlayer(yurl, args=['-o', 'hdmi'])
            return self.player.duration()

    def stop(self):
        self.player.stop()
        self._play = False
        self.player = None
        return False

    def skip(self):
        if self.playlist == True:
            self.player.stop()
            return True
        else:
            self.player.stop()
            return False

    def toggle(self):
        #false = not playing // true = playing
        if self.state == True:
            self.state = False
            self.player.pause()
        elif self.state == False:
            self.state = True
            self.player.play()
        else:
            return False

    def is_play(self):
        return self.player.can_control()
Exemplo n.º 11
0
def playFile(audioPath):
    player = OMXPlayer(audioPath,
                       dbus_name='org.mpris.MediaPlayer2.omxplayer1')
    time.sleep(2.5)  # establish player
    try:
        while player.is_playing():
            time.sleep(0.3)
            ringSensor.readTrill()
            if ringSensor.getNumTouches() >= 3:
                print("3 ring sensor touches - stopping")
                player.pause()
    except:
        player.quit()
    player.quit()
Exemplo n.º 12
0
    def initPlayer(self, mediaFile):

        logger.info("Creating main omxplayer with file : " + mediaFile.path)

        dbusName = 'org.mpris.MediaPlayer2.omxplayer1'

        player = OMXPlayer(mediaFile.path,
                           dbus_name=dbusName,
                           args=['--no-osd', '-o', self.outputDevice])

        player.pause()

        self.paused = True

        return player
Exemplo n.º 13
0
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
class videoPlayer:
    def __init__(self, videoPath):
        self.videoPath = videoPath
        self.classPlayer = OMXPlayer(self.videoPath)
        sleep(0.2)
        self.classPlayer.pause()

    def playVideo(self):
        self.classPlayer.play()

    def end(self):
        return self.classPlayer.is_playing()

    def length(self):
        return self.classPlayer.duration()

    def freeze(self):
        self.classPlayer.quit()
Exemplo n.º 15
0
#!/usr/bin/env python3

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

VIDEO_PATH00 = Path("/home/pi/Miac/01.mp4")
player00 = OMXPlayer(VIDEO_PATH00, args='-b')
player00.pause()
player00.hide_video()
sleep(2)

VIDEO_PATH = Path("/home/pi/Miac/03.mp4")
player = OMXPlayer(VIDEO_PATH)
sleep(1)
player.quit()

player.load(VIDEO_PATH)
sleep(2)

player.pause()
print(player.stopEvent)
sleep(2)
player.hide_video()
sleep(2)
player.show_video()
player.quit()

sleep(3)
player00.quit()
Exemplo n.º 16
0
# pg.mixer.set_num_channels(12)
#
# mixer = pg.mixer
# channel0 = mixer.Channel(0)
# channel1 = mixer.Channel(1)

# music to play
# office_theme = mixer.Sound("music/office_theme_song.wav")
# agni_kai = mixer.Sound("music/last_agni_kai.wav")
# succession_theme = mixer.Sound("music/succession_theme.wav")

# music to play
office_theme = OMXPlayer(Path('music/office_theme_song.wav'),
                         dbus_name='org.mpris.MediaPlayer2.omxplayer5',
                         args='--loop')
office_theme.pause()
agni_kai = OMXPlayer(Path('music/last_agni_kai.wav'),
                     dbus_name='org.mpris.MediaPlayer2.omxplayer6',
                     args='--loop')
agni_kai.pause()
succession_theme = OMXPlayer(Path('music/succession_theme.wav'),
                             dbus_name='org.mpris.MediaPlayer2.omxplayer7',
                             args='--loop')
succession_theme.pause()
fun_song = OMXPlayer(Path('music/fun_song.wav'),
                     dbus_name='org.mpris.MediaPlayer2.omxplayer8',
                     args='--loop')
fun_song.pause()
thrones_theme = OMXPlayer(Path('music/thrones_theme.wav'),
                          dbus_name='org.mpris.MediaPlayer2.omxplayer9',
                          args='--loop')
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()

sleep(5)

player.quit()
Exemplo n.º 18
0
class VideoPlayer:
    def __init__(self):
        self.process = None
        self.cmd = ""
        self.args = ""
        self.path = ""
        self.player = None

    def composeCommand(self):
        # split the command and use
        # the 'glob' module to expand the * wildchar
        #self.cmd = 'omxplayer --loop --no-osd --win "0 0 {} {}" --crop {},{},{},{} {}'.format(SCREENW, SCREENH, CROPX1, CROPY1, CROPX2, CROPY2, videoFileLocation)
        self.cmd = 'omxplayer --no-osd'
        self.args = shlex.split(self.cmd)
        self.args = self.args[:-1] + glob.glob(self.args[-1])

    def loadVideo(self, path):
        self.path = path
        print(self.path)
        #~ self.cmd = 'omxplayer --no-osd {}'.format(videoName)
        #~ self.args = shlex.split( self.cmd )
        #~ self.args = self.args[:-1] + glob.glob( self.args[-1] )

        #~ # Open omxplayer
        #~ try:
        #~ print( " load the video " )
        #~ self.process = Popen( self.args, stdin=PIPE, stdout=PIPE )
        #~ print("This is the omxplayer process id: ",  self.process.pid )

        #~ except:
        #~ print("something went wrong")
        #~ quit()

    def play(self):
        #~ print("play")
        if self.player is None:
            self.player = OMXPlayer(self.path,
                                    args=['--no-osd', '--adev', 'local'])
        #~ self.player.play()
        #~ self.process.stdin.write(b'i')
        #~ self.process.stdin.flush()

    def stop(self):
        #~ print("stop")
        if self.player is not None:
            self.player.quit()
            self.player = None

    def pause(self):
        #~ print("pause")
        self.player.pause()
        #self.process.stdin.write(b'p')
        #self.process.stdin.flush()

    def kill(self):
        # quit omxplayer
        self.player.stop()
        #~ self.process.stdin.write(b'q')
        #~ self.process.stdin.flush()
        #~ self.process.stdin.close()

    def is_ended(self):
        if self.player is not None:
            #~ print(self.player.position())
            # ~ if self.player.position() > 10 or self.player.duration() - self.player.position() < 0.2:
            if self.player.duration() - self.player.position() < 1:
                return True
            else:
                return False

    def next(self, videoName):
        self.stop()
        self.loadVideo(videoName)
        self.play()
Exemplo n.º 19
0
class MusicPlayer():
    def __init__(self, playlist, logger):
        self.playlist = playlist
        self.idx = 0
        self.logger = logger
        self.omxplayer = None

    def get_song_real_url(self, song_url):
        try:
            htmldoc = urlopen(song_url).read().decode('utf8')
        except:
            return (None, None, 0, 0)

        content = json.loads(htmldoc)

        try:
            song_link = content['data']['songList'][0]['songLink']
            song_name = content['data']['songList'][0]['songName']
            song_size = int(content['data']['songList'][0]['size'])
            song_time = int(content['data']['songList'][0]['time'])
        except:
            self.logger.error('get real link failed')
            return (None, None, 0, 0)

        return song_name, song_link, song_size, song_time

    def play(self):
        self.logger.debug('MusicPlayer play')
        song_url = "http://music.baidu.com/data/music/fmlink?" +\
            "type=mp3&rate=320&songIds=%s" % self.playlist[self.idx]['id']
        song_name, song_link, song_size, song_time =\
            self.get_song_real_url(song_url)

        self.play_mp3_by_link(song_link, song_name, song_size, song_time)

    def play_mp3_by_link(self, song_link, song_name, song_size, song_time):
        if song_link:
            self.omxplayer = OMXPlayer(song_link, ['-o', 'both'])
        else:
            self.omxplayer = None

    def pick_next(self):
        self.idx += 1
        if self.idx > len(self.playlist) - 1:
            self.idx = 0

        if self.omxplayer and self.omxplayer.can_play():
            self.omxplayer.quit()

    def pick_previous(self):
        self.idx -= 1
        if self.idx < 0:
            self.idx = 0

        if self.omxplayer and self.omxplayer.can_play():
            self.omxplayer.quit()

    def pause(self):
        if self.omxplayer and self.omxplayer.can_pause():
            self.omxplayer.pause()

    def resume(self):
        if self.omxplayer and self.omxplayer.can_play():
            self.omxplayer.play()

    def is_play_done(self):
        try:
            return self.omxplayer is None or\
                self.omxplayer.can_play() is None
        except Exception as e:
            self.logger.error(e)
            return False

    def stop(self):
        self.playlist = []
        if self.omxplayer:
            self.omxplayer.quit()
Exemplo n.º 20
0
class OmxPlayer(BasePlayer):
    def __init__(self, hplayer, name):
        super().__init__(hplayer, name)

        self._validExt = [
            'mp4', 'm4v', 'mkv', 'avi', 'mov', 'flv', 'mpg', 'wmv', '3gp',
            'mp3', 'aac', 'wma', 'wav', 'flac', 'aif', 'aiff', 'm4a', 'ogg',
            'opus', 'webm', 'jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff'
        ]

        self._thread = None
        self._runflag = threading.Event()
        self.player = None

    ############
    ## private METHODS
    ############

    # MPV THREAD
    def _mpv_thread(self):

        self.emit('player-ready')
        self.emit('status', self.status())

        self.log("player ready")

        while self.isRunning():

            self._runflag.wait(0.37)
            if self._runflag.isSet():
                self.update('time', round(self.player.position(), 2))
                time.sleep(0.05)

        self.isRunning(False)
        return

    def _onPlay(self, p):
        self.update('isPlaying', True)
        self.update('isPaused', False)
        self.emit('playing')
        self._runflag.set()
        self.log('play')

    def _onPause(self, p):
        self.update('isPlaying', False)
        self.update('isPaused', True)
        self.emit('paused')
        self._runflag.clear()
        self.log('pause')

    def _onExit(self, p, c):
        self.player._connection._bus.close()
        self.player._connection = None
        self.player = None
        self._runflag.clear()
        self.update('isPlaying', False)
        self.update('isPaused', False)
        self.emit('end')
        self.emit('stopped')
        self.log('stop')

    ##########
    ## Inherited "abstract" METHODS overloads
    ##########

    #
    # Start the player:
    #   - instantiate mpv subprocess
    #   - connect IPC socket i/o
    #
    def _start(self):

        # Playback thread
        self._thread = threading.Thread(target=self._mpv_thread)
        self._thread.start()

    #
    # Exit the player
    #   - stop subprocess
    #   - close IPC socket
    #
    def _quit(self):
        self.isRunning(False)
        if self._thread:
            # self.log("stopping process thread")
            self._thread.join()
        self.log("stopped")

    def _play(self, path):
        self.log("play", path)

        if self.player:
            self.player.quit()

        self.player = OMXPlayer(path,
                                dbus_name='org.mpris.MediaPlayer2.omxplayer2')
        self.player.playEvent += self._onPlay
        self.player.pauseEvent += self._onPause
        # self.player.stopEvent += self._onStop
        self.player.exitEvent += self._onExit
        self.player.play()
        # self.player.set_video_pos(0,0,100,100)

        # self.update('duration', round(self.player.duration(),2))

    def _stop(self):
        if self.player:
            self.player.stop()

    def _pause(self):
        if self.player:
            self.player.pause()

    def _resume(self):
        if self.player:
            self.player.play()

    def _seekTo(self, milli):
        if self.player:
            self.player.set_position(milli / 1000)
        # self.log("seek to", milli/1000)

    def _skip(self, milli):
        if self._status['time'] + milli / 1000 < self._status['duration']:
            if self.player:
                self.player.seek(milli / 1000)
        # self.log("skip", milli/1000)

    def _applyVolume(self, volume):
        if self.player:
            self.player.set_volume(volume / 10.0)
        self.log("VOLUME to", volume)
Exemplo n.º 21
0
class VideoPlayer(object):
    def __init__(self):
        self.player = None
        self.logger = LogObject('Video Player')
        self.args = ['-b']

        self.STATUS_MAP = {
            'volume': self._videoVolume,
            'length': self._videoLength,
            'playback': self._playbackStatus,
            'position': self._videoPosition
        }

        self.CONTROL_MAP = {
            'playpause': self._playPause,
            'stop': self._stop,
            'mute': self._mute,
            'unmute': self._unmute,
            'play': self._play,
            'pause': self._pause
        }

        self.SEEK_MAP = {'relative': self._seek, 'absolute': self._setPosition}

    def playUrl(self, url):

        if not self.player:
            self.player = OMXPlayer(url, args=self.args)
        else:
            self.player.load(url)

    def setVolume(self, volume):
        self._checkPlayerExist()
        try:
            self.player.set_volume(volume)
            return self.logger.writeAndReturnLog('VOL0003', {'volume': volume})
        except (AttributeError, OMXPlayerDeadError):
            self._raisePlayerError('VOL0004')

    def sendCommand(self, command):
        self._checkPlayerExist()
        try:
            return self.CONTROL_MAP[command]()
        except (AttributeError, OMXPlayerDeadError):
            self._raisePlayerError('CTRL0003')

    def _stop(self):
        self.player.quit()
        return self.logger.writeAndReturnLog('CTRL0004')

    def _mute(self):
        self.player.mute()
        return self.logger.writeAndReturnLog('CTRL0006')

    def _unmute(self):
        self.player.unmute()
        return self.logger.writeAndReturnLog('CTRL0007')

    def _playPause(self):
        self.player.play_pause()
        return self.logger.writeAndReturnLog('CTRL0005')

    def _play(self):
        self.player.play()
        return self.logger.writeAndReturnLog('CTRL0008')

    def _pause(self):
        self.player.pause()
        return self.logger.writeAndReturnLog('CTRL0009')

    def seek(self, option, time):
        self._checkPlayerExist()
        try:
            return self.SEEK_MAP[option](time)
        except (AttributeError, OMXPlayerDeadError):
            self._raisePlayerError('SEEK0007')

    def _seek(self, seekTime):
        self.player.seek(seekTime)
        return self.logger.writeAndReturnLog('SEEK0005',
                                             {'position': seekTime})

    def _setPosition(self, position):
        if position > self._videoLength() or position < 0:
            self._raisePlayerError('SEEK0004', {'position': position})
        self.player.set_position(position)
        return self.logger.writeAndReturnLog('SEEK0006',
                                             {'position': position})

    def _checkPlayerExist(self):
        if not self.player:
            self._raisePlayerError('CTRL0003')

    def videoStatus(self, status):
        if not self.player:
            self._raisePlayerError('STAT0003')
        try:
            return self.STATUS_MAP[status]()
        except (AttributeError, OMXPlayerDeadError):
            self._raisePlayerError('STAT0003')

    def _videoPosition(self):
        return self.player.position()

    def _videoLength(self):
        return self.player.duration()

    def _videoVolume(self):
        return self.player.volume()

    def _playbackStatus(self):
        return self.player.playback_status()

    def _raisePlayerError(self, logReference, variablesDict={}):
        returnMsg = self.logger.writeAndReturnLog(logReference, variablesDict)
        raise PlayerError(returnMsg)
Exemplo n.º 22
0
print("--------------")
print(GPIO.input(button))
print("--------------")

VIDEO_PATH = Path("cam_3d.mp4")
BLACK_PATH = Path("black_screen.mp4")
player_log = logging.getLogger("Player 1")

player_action = OMXPlayer(VIDEO_PATH, 
        dbus_name='org.mpris.MediaPlayer2.omxplayer1')
        
player_stop = OMXPlayer(BLACK_PATH, 
        dbus_name='org.mpris.MediaPlayer2.omxplayer2')

# it takes about this long for omxplayer to warm up and start displaying a picture on a rpi3
player_action.pause()
sleep(2.5)
player_stop.pause()
try:
    while True:
         # Button was pressed
         
        if ( GPIO.input(button) == GPIO.LOW ):
            sleep(1)
            try:
                if (player_action.is_playing() == True):
                    player_action.stop()
                    sleep(1)
                    player_action = OMXPlayer(VIDEO_PATH, dbus_name='org.mpris.MediaPlayer2.omxplayer1')
                else:
                    player_action.play()
Exemplo n.º 23
0
class VideoPlayer:
    def __init__(self,
                 VIDEO_NAME,
                 IMAGE_WIDTH,
                 IMAGE_HEIGHT,
                 USING_VLC=False,
                 audioPlayerRef=None,
                 pygameRef=None):

        self.USING_VLC = USING_VLC
        self.VIDEO_FILE = VIDEO_NAME
        #get a reference to the audio player
        self.audioPlayerRef = audioPlayerRef

        self.player = None

        if self.USING_VLC:
            if (pygameRef == None):
                print(
                    "VIDEOPLAYER ERROR: don't have a reference to pygame window!"
                )

            self.vlcInstance = vlc.Instance()
            #tmp (remove comment here) self.media = self.vlcInstance.media_new('/home/pi/code/' + self.VIDEO_FILE)
            self.media = self.vlcInstance.media_new(self.VIDEO_FILE)

            # Create new instance of vlc player
            self.player = self.vlcInstance.media_player_new()
            self.player.stop()

            # Pass pygame window id to vlc player, so it can render its contents there.
            win_id = pygameRef.display.get_wm_info()['window']
            self.player.set_xwindow(win_id)
            self.player.set_media(self.media)

            # TODO: correct the line below
            mouse.move(IMAGE_WIDTH, IMAGE_HEIGHT, True, 0)
        else:
            self.omx_stdin = None
            self.omx_process = None
            self.tot_sec = None

        self.STARTED = False
        self.PAUSED = False
        if (self.USING_VLC):
            print("VIDEOPLAYER: using VLC")
        else:
            print("VIDEOPLAYER: using OMX")

        # info about video
        self.info_video = {}
        self.chapters = self.get_chapters()
        self.curr_chapter = 0
        print('VIDEOPLAYER: info video \n\t# chapter:{}\n\t{}'.format(
            len(self.chapters), self.chapters))

    def start(self):
        print("VIDEOPLAYER: Starting video...")
        self.STARTED = True
        self.PAUSED = False

        if self.USING_VLC:
            self.player.play()
        else:
            if self.player:
                self.player.quit()
                self.player = None
            self.player = OMXPlayer(self.VIDEO_FILE, args=['--no-osd'])
        time.sleep(1)

    def stop(self):
        print("VIDEOPLAYER: Stopping video...")
        self.STARTED = False
        #TODO: is it necessary
        #self.PAUSED = True
        if self.USING_VLC:
            self.player.stop()
        else:
            self.player.quit()
            self.player = None

    def pause(self):
        print("VIDEOPLAYER: Pausing video...")
        # TODO: add some code here??
        #self.PAUSED = True #??

    def needUpdate(self):
        return (self.STARTED and self.player)

    def update(self):
        #print("VIDEOPLAYER: update")
        if self.USING_VLC:
            if self.player.get_length() - self.player.get_time(
            ) < 2000 and not self.PAUSED:
                print("VIDEOPLAYER VLC: a due secondi dalla fine")
                self.PAUSED = True
                self.player.set_pause(1)
        else:
            if self.player.duration() - self.player.position(
            ) < 2 and not self.PAUSED:
                print('VIDEOPLAYER OMX: a due secondi dalla fine')
                self.PAUSED = True
                self.player.pause()
        #self.printStatus()

    def printStatus(self):
        print("VIDEOPLAYER: started {}, paused {}".format(
            self.STARTED, self.PAUSED))

    def changeChapter(self, chapter):
        print("VIDEOPLAYER: change chapter")
        if chapter != 0:
            print("VIDEOPLAYER: chapter != 0")
            # in origin era così riga commentata)
            #if self.PAUSED == True:
            #if self.PAUSED == False:
            #print("VIDEOPLAYER: paused is true")
            if self.USING_VLC:
                self.player.set_pause(0)
            else:
                if self.player:
                    self.player.play()
            self.PAUSED = False

            if self.USING_VLC:
                self.handle_chapter_vlc(chapter)
            else:
                self.handle_chapter_omx(chapter)
        """
		if self.USING_VLC:
			if  self.player.get_length() - self.player.get_time() < 2000 and not self.PAUSED:
				self.PAUSED = True
				self.player.set_pause(1)
		else:
			if  self.player.duration() - self.player.position() < 2 and not self.PAUSED:
				print('...pausing video')
				self.PAUSED = True
				self.player.pause()
				
		"""
        """
		#not using language right now
		# return to italian language
		if self.audioPlayerRef:
			self.audioPlayerRef.switchToITA()
		"""

    def isPlaying(self):
        return self.STARTED

    def switch_language(self):
        print("Video: switch language...")
        if self.audioPlayerRef:
            self.audioPlayerRef.switchLanguage()
        if self.player:
            self.player.set_position(0)

    # get all chapters of video file
    def get_chapters(self):
        buff = sp.check_output([
            "ffmpeg", "-i", self.VIDEO_FILE, "-f", 'ffmetadata', "file.txt",
            '-y'
        ],
                               stderr=sp.STDOUT,
                               universal_newlines=True)
        #print(buff)
        self.chapters = []
        self.chapters_info = {}
        names = []
        i = 0
        for line in iter(buff.splitlines()):
            m = re.match(
                r".*Chapter #(\d+:\d+): start (\d+\.\d+), end (\d+\.\d+).*",
                line)
            if m != None and m.group(1) not in names:
                names.append(m.group(1))
                self.chapters.append({
                    "name": i + 1,
                    "start": float(m.group(2)),
                    "end": float(m.group(3))
                })
                i = i + 1
        if len(self.chapters) == 2:
            self.chapters[len(self.chapters) - 1]['name'] = 3
        return self.chapters

    # check where i am:
    # 0: before chapter 1
    # 1: chapter 1
    # 2: chapter 2
    # 3: chapter 3
    # 10 last chapter
    def pos2chapter(self, pos):
        # ~ print('actual position', pos)
        for x in self.chapters:
            if pos >= x['start'] / 1000 and pos <= x['end']:
                return x['name']
        if pos < self.chapters[0]['start']:
            return 0
        if pos > self.chapters[len(self.chapters) - 1]['end']:
            return self.chapters[len(self.chapters) - 1]['name']

    # vlc chapter manager
    def handle_chapter_vlc(self, c):
        print('VIDEOPLAYER VLC: going to', len(self.chapters), c)
        if len(self.chapters) == 2:
            if c == 3:
                print(1)
                self.player.set_chapter(1)
            if c == 1:
                print(2)
                self.player.set_chapter(0)
        else:
            self.player.set_chapter(c - 1)
        self.audioPlayerRef.stop()
        if c == 1:
            self.audioPlayerRef.start()
        self.curr_chapter = c

    # chapter manager
    def handle_chapter_omx(self, c):
        self.curr_chapter = self.pos2chapter(self.player.position())
        print('VIDEOPLAYER OMX: Handle chapter: from', self.curr_chapter, 'to',
              c)
        # ~ if c != curr_chapter and c in [f['name'] for f in chapters]:
        if c in [f['name'] for f in self.chapters]:
            cpt = self.chapters[[
                y for y, x in enumerate(self.chapters) if x['name'] == c
            ][0]]
            time.sleep(1)
            print('going to', cpt['start'])
            self.player.set_position(cpt['start'])
            time.sleep(1)
            self.audioPlayerRef.stop()
            if c == 1:
                self.audioPlayerRef.start()
            self.curr_chapter = c

    def kill(self):
        print("Kill video...")
        if self.USING_VLC:
            self.player.stop()
        else:
            self.player.quit()
            self.player = None
Exemplo n.º 24
0
videos.append(video('../shared/matrix.mp4', None, 'fill', 0, 1.0))
videos.append(video('../shared/river.mp4', None, 'fill', 0, 0.5))
videos.append(video('../shared/testcard.mp4', None, 'fill', 0, 0.35))
videos.append(video('../shared/timer.mp4', None, 'fill', 10, 0.35))

player_log = logging.getLogger("Player 1")


# Create player 1
player1 = OMXPlayer(videos[0].path, dbus_name='org.mpris.MediaPlayer2.omxplayer1', args=['--loop'])

player1.playEvent += lambda _: player_log.info("Play")
player1.pauseEvent += lambda _: player_log.info("Pause")
player1.stopEvent += lambda _: player_log.info("Stop")

player1.pause()
player1.hide_video()
player1.set_position(videos[0].start)
player1.set_volume(videos[0].volume)
player1.set_aspect_mode(videos[0].aspect)

# Show player 1
player1.show_video()
player1.play()

sleep(5)

# Load player 1 with video 2
player1.pause()
player1.hide_video()
player1.load(videos[1].path, pause=True)
Exemplo n.º 25
0
    osrs_t = 1  # Temperature oversampling x 1
    mode = 3  # Normal mode
    t_sb = 5  # Tstandby 1000ms
    filter = 0  # Filter off
    spi3w_en = 0  # 3-wire SPI Disable

    ctrl_meas_reg = (osrs_t << 5) | mode
    config_reg = (t_sb << 5) | (filter << 2) | spi3w_en

    writeReg(0xF4, ctrl_meas_reg)
    writeReg(0xF5, config_reg)


setup()
get_calib_param()

time.sleep(3)
player_sub = OMXPlayer(VIDEO_PATH_SUB)

time.sleep(3)
player_sub.set_position(0)
player_sub.pause()

if __name__ == '__main__':
    try:
        while True:
            readData()
            time.sleep(5)
    except KeyboardInterrupt:
        pass
Exemplo n.º 26
0
class VideoPlayer:
    def __init__(self, root, message_handler, data, name):
        self.root = root
        self.message_handler = message_handler
        self.data = data
        self.omx_player = None
        self.name = name
        self.omx_running = False
        self.status = 'EMPTY'
        self.total_length = 0.0
        self.bankslot_number = '*-*'
        self.start = -1.0
        self.end = -1.0
        self.rate = 1
        self.crop_length = 0.0
        self.location = ''
        self.load_attempts = 0
        self.alpha = 0

    def try_load(self, layer):
        load_attempts = 0
        while (load_attempts < 2):
            load_attempts = load_attempts + 1
            if self.load(layer):
                print('load success')
                return True
            else:
                print('load failed')
        self.message_handler.set_message('ERROR', 'failed to load')
        self.status = 'ERROR'
        return False

    def load(self, layer):
        #try:
        self.get_context_for_player()
        is_dev_mode, first_screen_arg, second_screen_arg = self.set_screen_size_for_dev_mode(
        )
        arguments = [
            '--no-osd', '--layer',
            str(layer), '--adev', 'local', '--alpha', '0', first_screen_arg,
            second_screen_arg
        ]
        if not is_dev_mode:
            arguments.append('--blank=0x{}'.format(
                self.data.get_background_colour()))
        self.status = 'LOADING'
        print('the location is {}'.format(self.location))
        if self.location == '':
            self.status = 'EMPTY'
            return True
        self.omx_player = OMXPlayer(self.location,
                                    args=arguments,
                                    dbus_name=self.name)
        self.omx_running = True
        self.total_length = self.omx_player.duration(
        )  # <-- uneeded once self.duration stores float
        if (self.end is -1):
            self.end = self.total_length
        if (self.start is -1):
            self.start = 0
        self.crop_length = self.end - self.start
        print('{}: the duration is {}'.format(self.name, self.total_length))
        if self.start > 0.9:
            self.set_position(self.start - 0.9)
        if 'show' in self.data.settings['sampler']['ON_LOAD']['value']:
            self.set_alpha_value(255)
        else:
            self.set_alpha_value(0)
        self.pause_at_start()
        return True
        #except (ValueError, SystemError) as e:
        #  print(e)
        #self.message_handler.set_message('ERROR', 'load attempt fail')
        #return False

    def pause_at_start(self):
        position = self.get_position()
        start_threshold = round(self.start - 0.02, 2)
        if position > start_threshold:
            if self.status == 'LOADING':
                self.status = 'LOADED'
                self.omx_player.pause()
        elif self.omx_running:
            self.root.after(5, self.pause_at_start)

    def start_video(self):
        if 'show' in self.data.settings['sampler']['ON_START']['value']:
            self.set_alpha_value(255)
        else:
            self.set_alpha_value(0)
        if 'play' in self.data.settings['sampler']['ON_START']['value']:
            self.status = 'PLAYING'
            self.omx_player.play()
        else:
            self.status = 'START'
        self.pause_at_end()

    def pause_at_end(self):
        position = self.get_position()
        end_threshold = self.end - 0.2
        if (position > end_threshold):
            self.status = 'FINISHED'
            self.omx_player.pause()

            print('its paused at end!')
        elif (self.omx_running):
            self.root.after(5, self.pause_at_end)

    def reload(self, layer):
        self.exit()
        self.omx_running = False
        self.try_load(layer)

    def is_loaded(self):
        return self.status is 'LOADED'

    def is_finished(self):
        return self.status is 'FINISHED'

    def get_position(self):
        try:
            return self.omx_player.position()
        except:
            print('{}: error get_position'.format(self.name))
            return -1

    def get_context_for_player(self):
        next_context = self.data.get_next_context()
        self.location = next_context['location']
        #self.total_length = next_context['length']
        self.start = next_context['start']
        self.end = next_context['end']
        self.bankslot_number = next_context['bankslot_number']
        self.rate = next_context['rate']

    def toggle_pause(self):
        self.omx_player.play_pause()
        self.status = self.omx_player.playback_status().upper()

    def toggle_show(self):
        if self.alpha > 127:
            self.show_toggle_on = False
            self.set_alpha_value(0)
        else:
            self.show_toggle_on = True
            self.set_alpha_value(255)

    def set_alpha_value(self, amount):
        self.omx_player.set_alpha(amount)
        self.alpha = amount

    def seek(self, amount):
        position = self.get_position()
        after_seek_position = position + amount
        if after_seek_position > self.start and after_seek_position < self.end:
            self.set_position(after_seek_position)
            #self.player.seek(amount)
        else:
            self.message_handler.set_message('INFO',
                                             'can not seek outside range')

    def change_rate(self, amount):
        new_rate = self.rate + amount
        if (new_rate > self.omx_player.minimum_rate()
                and new_rate < self.omx_player.maximum_rate()):
            updated_speed = self.omx_player.set_rate(new_rate)
            self.rate = new_rate
            print('max rate {} , min rate {} '.format(
                self.omx_player.maximum_rate(),
                self.omx_player.minimum_rate()))
            return new_rate
        else:
            self.message_handler.set_message(
                'INFO', 'can not set speed outside of range')
            return self.rate

    def set_position(self, position):
        self.omx_player.set_position(position)

    def exit(self):
        try:
            self.omx_player.quit()
            self.status = 'EMPTY'
            self.omx_running = False
        except:
            pass

    def set_screen_size_for_dev_mode(self):
        ## only dev mode is needed now that auto handles all modes... can be removed probably ...
        if self.data.settings['other']['DEV_MODE_RESET']['value'] == 'on':
            return True, '--win', '50,350,550,750'
        else:
            aspect_mode = self.data.settings['video']['SCREEN_MODE']['value']
            return False, '--aspect-mode', aspect_mode
Exemplo n.º 27
0
class Omx():
    def __init__(self):
        self.url = "None"
        self.player = None
        self.srt = None
        self.dvdplayer = None
        self.subs = 0
        self.audio_tracks = 0
        self.titles = 0
        return

    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

    def start_media(self, host, file):
        address = "http://" + str(host) + ":8090/" + file
        self.player = OMXPlayer(address.replace(" ", "%20"),
                                args=['-o', 'hdmi'])
        i = 0
        while not self.player.is_playing():
            time.sleep(1)
            i += 1
            if i >= 40:
                break
            return False
        return True

    def start_dvd(self):
        self.dvdplayer = mpv.MPV()
        self.dvdplayer.fullscreen = True
        self.dvdplayer['vo'] = 'rpi'
        self.dvdplayer['rpi-osd'] = 'yes'
        self.dvdplayer['osd-bar'] = 'yes'
        self.dvdplayer['osd-on-seek'] = 'msg-bar'
        self.dvdplayer['osd-level'] = '1'
        self.dvdplayer['osd-duration'] = '8000'
        self.dvdplayer['loop-file'] = 'no'
        self.dvdplayer['end'] = '-5'
        self.dvdplayer['osd-playing-msg'] = 'Now Playing Your DVD'
        self.dvdplayer['dvd-device'] = '/dev/nbd0'
        self.dvdplayer.play('dvd://')
        self.audio_tracks = 0
        self.subs = 0
        self.titles = 0
        return True

    def get_tracks(self):
        #Get the amount of audio tracks and subtitles avaible on DVD(May cause issues when more than 1 movie on DVD)
        self.subs = 0
        self.audio_tracks = 0
        print(self.dvdplayer._get_property('disc-titles', 'length'))
        for item in self.dvdplayer._get_property("track-list"):
            if item['type'] == 'sub':
                self.subs += 1
            if item['type'] == 'audio':
                self.audio_tracks += 1
        return

    def close_srt(self):
        if self.srt and self.srt.poll() is None:
            self.srt.terminate()
            self.srt.wait()

    def pause(self):
        if self.player:
            time.sleep(1)
            self.player.pause()
        self.close_srt()

    def mirror(self):
        self.make_pipe()
        self.player = OMXPlayer(NAMED_PIPE,
                                args=[
                                    '-o', 'hdmi', '--lavfdopts',
                                    'probesize:8000', '--timeout', '0',
                                    '--threshold', '0'
                                ])
        with open(NAMED_PIPE, "wb", 0) as output_stream:
            self.srt = subprocess.Popen([
                "stransmit", "srt://:8090?mode=server&pbkeylen=0", "file://con"
            ],
                                        stdout=output_stream)
        return

    def make_pipe(self):
        if os.path.exists(NAMED_PIPE):
            os.remove(NAMED_PIPE)
        os.mkfifo(NAMED_PIPE)
Exemplo n.º 28
0
player2.playEvent += lambda _: print("Play event triggered for 2"
                                     )  #player_log.info("Play")
player2.pauseEvent += lambda _: print("Pause event triggered for 2"
                                      )  #player_log.info("Pause")
player2.stopEvent += lambda _: print("Stop event triggered for 2"
                                     )  #player_log.info("Stop")

time.sleep(2.5)

player2.play()
# it takes about this long for omxplayer to warm up and start displaying a picture on a rpi3
time.sleep(15.5)

player2.set_position(20)
player2.pause()

time.sleep(2)

#player.set_aspect_mode('stretch')
#player.set_video_pos(0, 0, 200, 200)
player2.play()

time.sleep(5)
player2.pause()
player2.load(VIDEO_1_PATH)
player2.play()
#player1.play()
time.sleep(5)

#player1.quit()
Exemplo n.º 29
0
class Video(Player):
    """Video player class."""
    def __init__(self):
        """Init as Player."""
        super(Video, self).__init__()
        self.logger = logging.getLogger("oxo")
        self.close_player = False
        self.stopped = False

    @classmethod
    def filepath(cls, clip):
        """Return disk location of a clip."""
        return os.path.join(DATA_DIR, "clips", clip["filename"])

    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")

    @classmethod
    def interact(cls, line, stdin):
        """Enqueue clips continuously through mplayer STDIN."""
        start_playback = "Starting playback..."

        logger = logging.getLogger("oxo")
        if start_playback in line:
            nextclip = cls.get_next()
            path = cls.filepath(nextclip)
            cmd = "loadfile {} 1\n".format(path)
            logger.info("Enqueued clip {}".format(nextclip['filename']))
            stdin.put(cmd)

    @classmethod
    def get_next(cls):
        """Select recently added video or a random one from db."""
        q = Query()
        q_incoming = db.search(q.incoming == True)
        if len(q_incoming) > 0:
            rv = q_incoming[0]
            db.update({"incoming": False}, q.incoming == True)
            logger.info("Enqueuing shortlisted clip {}".format(rv["filename"]))
        else:
            q = Query()
            try:
                q_clips = db.search(q.type == "clip")
            except JSONDecodeError:
                rv = None
            else:
                rv = choice(q_clips) if len(q_clips) > 0 else None
        return rv

    def stop(self):
        """Quit omxplayer instance."""
        self.logger.debug("Stopping {} player...".format(
            self.__class__.__name__))
        self.stopped = True
        if self.running:
            self.player.quit()
            self.logger.info("{} stopped".format(self.__class__.__name__))
        else:
            self.logger.debug("{} did not play".format(
                self.__class__.__name__))
Exemplo n.º 30
0
class Player:

    def __init__(self, video_file):
        self.player = None
        self.path = ''
        self.load(video_file)

    def load(self, video_file):
        print('Player loading {0}'.format(video_file))
        #if self.player != None:
        #    self.player.stop()
        #    del self.player
        self.path = os.path.join(media_dir, video_file)
        if self.player is None:
            self.player = OMXPlayer(self.path, args=['--loop', '--blank', '-o', 'both'])
        else:
            self.player.load(self.path)
        self.player.stopEvent += lambda _: self._complete()
        self.player.pauseEvent += lambda _: self._pauseEvent()
        self.player.playEvent += lambda _: self._playEvent()
        self.player.positionEvent += lambda _: self._positionEvent()
        self.player.seekEvent += lambda _: self._seekEvent()

    def _complete(self):
        print('Playback finished.')
   
    def _pauseEvent(self):
        print('Player pause event.')
   
    def _playEvent(self):
        print('Player play event.')

    def _positionEvent(self):
        print('Player position event.')

    def _positionEvent(self):
        print('Player seek event.')

    def set_pause(self, p):
        if p:
            self.player.pause()
        else:
            self.player.play()

    def get_pause(self):
        if self.player.is_playing():
            return False
        else:
            return True

    def toggle_pause(self):
        if self.player.is_playing():
            self.player.pause()
        else:
            self.player.play()

    def stop(self):
        self.player.stop()

    def quit(self):
        self.player.quit()

    def reload(self):
        print('Reloading {0}'.format(self.path))
        self.load(self.path)

    def get_path(self):
        return self.path
Exemplo n.º 31
0
from pathlib import Path
from time import sleep
import logging
#import RPi.GPIO as GPIO

#GPIO.setmode (GPIO.BOARD)
#GPIO.setwarnings (False)

VIDEO_PATH = "/home/pi/Desktop/elephant.mp4"
player_log = logging.getLogger("Player1")


intro = OMXPlayer(VIDEO_PATH, ['-o', 'local'], dbus_name='org.mpris.MediaPlayer2.omxplayer1')

intro.playEvent += lambda _: player_log.info("Play")
intro.pauseEvent += lambda _: player_log.info("Pause")
intro.stopEvent += lambda _: player_log.info("Stop")

sleep(2.5)

intro.set_position(5)
intro.pause()

sleep(1)
intro.set_aspect_mode("letterbox")
intro.set_video_pos(50,100,1000,1000)

intro.play()

sleep(5)
intro.quit()
Exemplo n.º 32
0
player_log = logging.getLogger("Player 1")
try:
    player = OMXPlayer("/home/pi/Projects/MuzeApp/media.mp4",
                       args=[
                           '--loop', '-o', 'both', '--no-osd', '--win',
                           '0 0 ' + m_width + ' ' + m_height
                       ],
                       dbus_name='org.mpris.MediaPlayer2.omxplayer1' +
                       str(random.randint(0, 99)))
except Exception as e:
    print(e)
player.playEvent += lambda _: player_log.info("Play")
player.pauseEvent += lambda _: player_log.info("Pause")
player.stopEvent += lambda _: player_log.info("Stop")
time.sleep(5)
player.pause()
player.set_alpha(0)

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

#set GPIO Pins
GPIO_TRIGGER = 23
GPIO_ECHO = 24

#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

measurements = []
lostDetectionCounterMax = lostInTime * 1000 / delay  #Iteration counts for deactivation
class MusicPlayer(QThreadWithLogging):
    def __init__(self):
        QThreadWithLogging.__init__(self)
        self.playlist = []
        self.process = None
        self.process_util = None
        self.player = None
        self.lock = Lock()

        self.dbus_increment = 1
        if capable_gpio:
            gpio.setmode(gpio.BCM)
            gpio.setup(18, gpio.OUT)

    @pyqtSlot(list)
    def push_to_playlist(self, pathes):
        self.log(f'lock by push_to_playlist')
        with self.lock:
            self.log(f'push {pathes}')
            self.playlist += pathes
        self.log(f'unlock')

    @pyqtSlot(result=list)
    def get_playlist(self):
        self.log(f'lock by push_to_playlist')
        with self.lock:
            playlist = list(self.playlist)
        self.log(f'unlock')
        return playlist

    @pyqtSlot()
    def play_unstoppable_music(self, mp3_path):
        self.log(f'begin force playing {mp3_path}')
        if capable_gpio:
            gpio.output(18, gpio.HIGH)
        try:
            if is_run_on_posix:
                player = OMXPlayer(mp3_path, args='--no-keys -o local',
                                   dbus_name=f'org.mpris.MediaPlayer2.omxplayer{self.dbus_increment}')
                self.dbus_increment += 1
                while player._process.returncode is None: time.sleep(1)
            else:
                process = subprocess.Popen(rf'python debug\run_mp3.py "{mp3_path}"')
                process.wait()
                process.terminate()
        except:
            self.log(f'failed to force playing {mp3_path}')
            self.log(traceback.format_exc())
        if capable_gpio:
            gpio.output(18, gpio.LOW)
        self.log(f'end force playing {mp3_path}')

    @pyqtSlot()
    def play_music(self, mp3_path):
        self.log(f'begin playing {mp3_path}')
        if capable_gpio:
            gpio.output(18, gpio.HIGH)
        try:
            if is_run_on_posix:
                self.player = OMXPlayer(mp3_path, args='--no-keys -o local',
                                        dbus_name=f'org.mpris.MediaPlayer2.omxplayer{self.dbus_increment}')
                self.dbus_increment += 1
                while self.player._process.returncode is None: time.sleep(1)
            else:
                self.process = subprocess.Popen(rf'python debug\run_mp3.py "{mp3_path}"')
                self.process_util = psutil.Process(pid=self.process.pid)
                self.process.wait()
                self.process.terminate()
        except:
            self.log(f'failed to playing {mp3_path}')
            self.log(traceback.format_exc())
        if capable_gpio:
            gpio.output(18, gpio.LOW)
        self.log(f'end playing {mp3_path}')

    def run(self):
        while not self.isFinished():
            if len(self.playlist) > 0:
                self.log(f'lock by running')
                with self.lock:
                    try:
                        self.play_music(self.playlist[0])
                    except:
                        self.log(traceback.format_exc())
                    del self.playlist[0]
                self.log('unlock')

    @pyqtSlot()
    def music_pause(self):
        try:
            if is_run_on_posix:
                self.player.pause()
                gpio.output(18, gpio.LOW)
            else:
                if self.process:
                    self.process_util.suspend()
        except Exception as e:
            self.log(f'failed to pause music')
            self.log(traceback.format_exc())

    @pyqtSlot()
    def music_resume(self):
        try:
            if is_run_on_posix:
                self.player.play()
                gpio.output(18, gpio.HIGH)
            else:
                if self.process:
                    self.process_util.resume()
        except Exception as e:
            self.log(f'failed to pause music')
            self.log(traceback.format_exc())

    @pyqtSlot()
    def close(self):
        try:
            if is_run_on_posix:
                self.player.quit()
                gpio.output(18, gpio.LOW)
            else:
                self.process.terminate()
        except Exception as e:
            self.log(f'failed to close music')
            self.log(traceback.format_exc())