예제 #1
0
def playVideoGo(video_name, start=0, length=0):
    print "Incoming video request"
    videofile_path = "video/" + video_name
    # TODO check is file en with mp4 or mov
    print "video to play: " + videofile_path
    video = OMXPlayer(videofile_path, pause=True)

    # set video clip duration
    if start > 0:
        video.set_position(start)

    # set video clip duration
    if length == 0:
        dur = video.duration()
        durint = int(dur)
        video.play()
        time.sleep(durint)
    else:
        video.play()
        print length
        time.sleep(length)

    print("Stop playing")
    video.quit()
    return "Video file played, lol"
예제 #2
0
def playVideoGo(video_name, start=0, length=0):
    print "Incoming video request"
    videofile_path = "video/"+ video_name 
    # TODO check is file en with mp4 or mov
    print "video to play: " + videofile_path  
    video = OMXPlayer(videofile_path, pause=True)
   
    # set video clip duration
    if start > 0:
        video.set_position(start)

    # set video clip duration
    if length == 0:
        dur = video.duration()
        durint = int(dur)
        video.play()
        time.sleep(durint)  
    else:
        video.play()
        print length
        time.sleep(length)

    print("Stop playing")
    video.quit()
    return "Video file played, lol"
예제 #3
0
 def thread_target(self):
     while True:
         self.recData = com.Receive()
         #ここに受け取ったデータ: recDataをphantomからrealに変換し、
         #real側でくっつけて、返すものが求められる
         if (self.recData != 0 and self.recData is not None):
             #<Merge>
             global movName
             movName = dictSP[str(self.recData)] + "-" + movName
             if os.path.exists("movs/" + movName + ".mp4") is False:
                 movName = "NA"
             #<Playing>
             print "startPlay"
             player = OMXPlayer("movs/" + movName + ".mp4")
             player.play()
             time.sleep(player.duration() - 5)
             com.Send(int(dictPS.get(dictMA.get(movName, "NA"), "0")))
             time.sleep(5)
             #player.pause()
             #if you got to quit you can't re-open
             player.quit()
             print "endPlay"
         #このあとに静止画を表示するなら、dictMA[movName]
         #<loopTest
         self.forTesCount += 1
         if self.forTesCount % 1000 == 0:
             print "recNOW"
         #loopTest>
         time.sleep(0.01)
예제 #4
0
class Controller(object):
    def __init__(self):
        pass

    def check_new_files(self):
        '''
        check new files from _DIR
        '''
        self._files = []
        for files in os.listdir(_DIR):
            if files.endswith(('wmv', 'mp4', 'mov', 'avi')):
               self._files.append(os.path.join(_DIR, files))
            else:
                pass

    def play_files(self):
        '''
        Play all the files sequentially
        '''
        self.idx = 0
        while True:
            # Loop over list of files
            self.current_file = self._files[self.idx]
            self.idx = (self.idx + 1) % len(self._files)
            self.next_file = self._files[self.idx]
            # Play files one after the other
            self.player(self.current_file)
            
    def player(self, current_file):
        print(current_file,'\n','\tPlaying')
        # Set output window size
        self.omx = OMXPlayer(current_file, args=["--win", " 0,0,640,480"])
        self.omx.play()
        try:
            self.omx.set_position(15.0)
            while True:
                try:
                    if not(self.omx.playback_status()):
                        # If file ended.. stop playback
                        print('\n\tStopped\n')
                        self.omx.stop()
                        break
                    
                    else:
                        # Print time elapsed
                        print('\r\t','{0:.2f}'.format(self.omx.position()),
                              '/', '{0:.2f}'.format(self.omx.duration())+
                              ' seconds', end = ''),
                        sys.stdout.flush()
                    
                except Exception, e:
                    # dBUS exception for file that 
                    # finished playing. Ignore!
                    pass

        except KeyboardInterrupt, e:
            # Catch Ctrl+C and stop playing
            # current file
            print('Stopping Playback..', e)
            self.omx.stop()
예제 #5
0
def createPlayer(filepath):
    try:
        global player
        global video_opened
        global clip_duration
        player = OMXPlayer(filepath, args=['--no-osd','-o','both','--win','0 0 450 300'])
        clip_duration = player.duration()
        video_opened = 1
        logging.getLogger('omxplayer.play').addHandler(logging.NullHandler()) #silence logging handlers message
    except Exception as e:
        print("Trying to open video again: %s" % e)
        sleep(1)
        exit()
예제 #6
0
def testVideo(video_id=None):
    print "Incoming video request"
    vid1 = OMXPlayer(TEST_MEDIA_FILE_1, pause=True)
    print("Start playing")
    vid1.set_position(70)
    dur = vid1.duration()
    print dur
    vid1.play()
    sleep(2)
    print("Stop playing")
    vid1.pause()
    time.sleep(2)
    vid1.load(TEST_MEDIA_FILE_2)
    vid1.play()
    sleep(2)
    print("Exit")
    vid1.quit()
예제 #7
0
def testVideo(video_id=None):
    print "Incoming video request"
    vid1 = OMXPlayer(TEST_MEDIA_FILE_1, pause=True)
    print("Start playing")
    vid1.set_position(70)
    dur = vid1.duration()
    print dur
    vid1.play()
    sleep(2)
    print("Stop playing")
    vid1.pause()
    time.sleep(2)
    vid1.load(TEST_MEDIA_FILE_2)
    vid1.play()
    sleep(2)
    print("Exit")
    vid1.quit()
예제 #8
0
class VideoOmxplayerPlugin(Plugin):
    video_extensions = {
        '.avi', '.flv', '.wmv', '.mov', '.mp4', '.m4v', '.mpg', '.mpeg', '.rm',
        '.swf', '.vob'
    }

    default_torrent_ports = [6881, 6891]
    torrent_state = {}

    def __init__(self,
                 args=[],
                 media_dirs=[],
                 download_dir=None,
                 torrent_ports=[],
                 *argv,
                 **kwargs):
        super().__init__(*argv, **kwargs)

        self.args = args
        self.media_dirs = set(
            filter(
                lambda _: os.path.isdir(_),
                map(lambda _: os.path.abspath(os.path.expanduser(_)),
                    media_dirs)))

        if download_dir:
            self.download_dir = os.path.abspath(
                os.path.expanduser(download_dir))
            if not os.path.isdir(self.download_dir):
                raise RuntimeError(
                    'download_dir [{}] is not a valid directory'.format(
                        self.download_dir))

            self.media_dirs.add(self.download_dir)

        self.player = None
        self.videos_queue = []
        self.torrent_ports = torrent_ports if torrent_ports else self.default_torrent_ports

    def play(self, resource):
        if resource.startswith('youtube:') \
                or resource.startswith('https://www.youtube.com/watch?v='):
            resource = self._get_youtube_content(resource)
        elif resource.startswith('magnet:?'):
            response = self.download_torrent(resource)
            resources = response.output
            if resources:
                self.videos_queue = resources
                resource = self.videos_queue.pop(0)
            else:
                error = 'Unable to download torrent {}'.format(resource)
                logging.warning(error)
                return Response(errors=[error])

        logging.info('Playing {}'.format(resource))

        if self.player:
            try:
                self.player.stop()
                self.player = None
            except Exception as e:
                logging.exception(e)
                logging.warning(
                    'Unable to stop a previously running instance ' +
                    'of OMXPlayer, trying to play anyway')

        try:
            self.player = OMXPlayer(resource, args=self.args)
            self._init_player_handlers()
        except DBusException as e:
            logging.warning('DBus connection failed: you will probably not ' +
                            'be able to control the media')
            logging.exception(e)

        return self.status()

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

    def stop(self):
        if self.player:
            self.player.stop()
            self.player.quit()
            self.player = None

        return self.status()

    def voldown(self):
        if self.player:
            self.player.set_volume(max(-6000, self.player.volume() - 1000))
        return self.status()

    def volup(self):
        if self.player:
            self.player.set_volume(min(0, self.player.volume() + 1000))
        return self.status()

    def back(self):
        if self.player:
            self.player.seek(-30)
        return self.status()

    def forward(self):
        if self.player:
            self.player.seek(+30)
        return self.status()

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

        if self.videos_queue:
            video = self.videos_queue.pop(0)
            return self.play(video)

        return Response(output={'status': 'no media'}, errors=[])

    def hide_subtitles(self):
        if self.player: self.player.hide_subtitles()
        return self.status()

    def hide_video(self):
        if self.player: self.player.hide_video()
        return self.status()

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

    def load(self, source, pause=False):
        if self.player: self.player.load(source, pause)
        return self.status()

    def metadata(self):
        if self.player: return Response(output=self.player.metadata())
        return self.status()

    def mute(self):
        if self.player: self.player.mute()
        return self.status()

    def unmute(self):
        if self.player: self.player.unmute()
        return self.status()

    def seek(self, relative_position):
        if self.player: self.player.seek(relative_position)
        return self.status()

    def set_position(self, position):
        if self.player: self.player.set_seek(position)
        return self.status()

    def set_volume(self, volume):
        # Transform a [0,100] value to an OMXPlayer volume in [-6000,0]
        volume = 60.0 * volume - 6000
        if self.player: self.player.set_volume(volume)
        return self.status()

    def status(self):
        state = PlayerState.STOP.value

        if self.player:
            state = self.player.playback_status().lower()
            if state == 'playing': state = PlayerState.PLAY.value
            elif state == 'stopped': state = PlayerState.STOP.value
            elif state == 'paused': state = PlayerState.PAUSE.value

            return Response(
                output=json.dumps({
                    'source': self.player.get_source(),
                    'state': state,
                    'volume': self.player.volume(),
                    'elapsed': self.player.position(),
                    'duration': self.player.duration(),
                    'width': self.player.width(),
                    'height': self.player.height(),
                }))
        else:
            return Response(
                output=json.dumps({'state': PlayerState.STOP.value}))

    def on_play(self):
        def _f(player):
            get_bus().post(VideoPlayEvent(video=self.player.get_source()))

        return _f

    def on_pause(self):
        def _f(player):
            get_bus().post(VideoPauseEvent(video=self.player.get_source()))

        return _f

    def on_stop(self):
        def _f(player):
            get_bus().post(VideoStopEvent())

        return _f

    def _init_player_handlers(self):
        if not self.player:
            return

        self.player.playEvent += self.on_play()
        self.player.pauseEvent += self.on_pause()
        self.player.stopEvent += self.on_stop()

    def search(self, query, types=None, queue_results=False, autoplay=False):
        results = []
        if types is None:
            types = {'youtube', 'file', 'torrent'}

        if 'file' in types:
            file_results = self.file_search(query).output
            results.extend(file_results)

        if 'torrent' in types:
            torrent_results = self.torrent_search(query).output
            results.extend(torrent_results)

        if 'youtube' in types:
            yt_results = self.youtube_search(query).output
            results.extend(yt_results)

        if results:
            if queue_results:
                self.videos_queue = [_['url'] for _ in results]
                if autoplay:
                    self.play(self.videos_queue.pop(0))
            elif autoplay:
                self.play(results[0]['url'])

        return Response(output=results)

    @classmethod
    def _is_video_file(cls, filename):
        is_video = False
        for ext in cls.video_extensions:
            if filename.lower().endswith(ext):
                is_video = True
                break

        return is_video

    def file_search(self, query):
        results = []
        query_tokens = [_.lower() for _ in re.split('\s+', query.strip())]

        for media_dir in self.media_dirs:
            logging.info('Scanning {} for "{}"'.format(media_dir, query))
            for path, dirs, files in os.walk(media_dir):
                for f in files:
                    if not self._is_video_file(f):
                        continue

                    matches_query = True
                    for token in query_tokens:
                        if token not in f.lower():
                            matches_query = False
                            break

                    if not matches_query:
                        continue

                    results.append({
                        'url': 'file://' + path + os.sep + f,
                        'title': f,
                    })

        return Response(output=results)

    def youtube_search(self, query):
        logging.info('Searching YouTube for "{}"'.format(query))

        query = urllib.parse.quote(query)
        url = "https://www.youtube.com/results?search_query=" + query
        response = urllib.request.urlopen(url)
        html = response.read()
        soup = BeautifulSoup(html, 'lxml')
        results = []

        for vid in soup.findAll(attrs={'class': 'yt-uix-tile-link'}):
            m = re.match('(/watch\?v=[^&]+)', vid['href'])
            if m:
                results.append({
                    'url': 'https://www.youtube.com' + m.group(1),
                    'title': vid['title'],
                })

        logging.info(
            '{} YouTube video results for the search query "{}"'.format(
                len(results), query))

        return Response(output=results)

    @classmethod
    def _get_youtube_content(cls, url):
        m = re.match('youtube:video:(.*)', url)
        if m: url = 'https://www.youtube.com/watch?v={}'.format(m.group(1))

        proc = subprocess.Popen(['youtube-dl', '-f', 'best', '-g', url],
                                stdout=subprocess.PIPE)

        return proc.stdout.read().decode("utf-8", "strict")[:-1]

    def torrent_search(self, query):
        logging.info(
            'Searching matching movie torrents for "{}"'.format(query))
        request = urllib.request.urlopen(
            urllib.request.Request(
                'https://api.apidomain.info/list?' +
                urllib.parse.urlencode({
                    'sort': 'relevance',
                    'quality': '720p,1080p,3d',
                    'page': 1,
                    'keywords': query,
                }),
                headers={
                    'User-Agent':
                    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
                    '(KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
                }))

        results = [{
            'url': _['items'][0]['torrent_magnet'],
            'title': _['title'],
        } for _ in json.loads(request.read())['MovieList']]

        return Response(output=results)

    def download_torrent(self, magnet):
        import libtorrent as lt

        if not self.download_dir:
            raise RuntimeError(
                'No download_dir specified in video.omxplayer configuration')

        ses = lt.session()
        ses.listen_on(*self.torrent_ports)

        info = lt.parse_magnet_uri(magnet)
        logging.info('Downloading "{}" to "{}" from [{}]'.format(
            info['name'], self.download_dir, magnet))

        params = {
            'save_path': self.download_dir,
            'storage_mode': lt.storage_mode_t.storage_mode_sparse,
        }

        transfer = lt.add_magnet_uri(ses, magnet, params)
        status = transfer.status()
        files = []

        self.torrent_state = {
            'url': magnet,
            'title': info['name'],
        }

        while (not status.is_seeding):
            status = transfer.status()
            torrent_file = transfer.torrent_file()
            if torrent_file:
                files = [
                    os.path.join(self.download_dir,
                                 torrent_file.files().file_path(i))
                    for i in range(0,
                                   torrent_file.files().num_files())
                    if self._is_video_file(torrent_file.files().file_name(i))
                ]

            self.torrent_state['progress'] = 100 * status.progress
            self.torrent_state['download_rate'] = status.download_rate
            self.torrent_state['upload_rate'] = status.upload_rate
            self.torrent_state['num_peers'] = status.num_peers
            self.torrent_state['state'] = status.state

            logging.info(
                ('Torrent download: {:.2f}% complete (down: {:.1f} kb/s ' +
                 'up: {:.1f} kB/s peers: {} state: {})').format(
                     status.progress * 100, status.download_rate / 1000,
                     status.upload_rate / 1000, status.num_peers,
                     status.state))

            time.sleep(5)

        return Response(output=files)

    def get_torrent_state(self):
        return self.torrent_state
예제 #9
0
def basic_func():
    try:
        print(commands)
        print(commands["play_pause"])
        directory = create_playlist()
        shuffle(directory)
        print("currently, my playlist is {}".format(directory))
        my_playlist_length = len(directory)
        my_song_index = 0
        my_song = directory[0]
        print("My song right now is {}".format(my_song))
        player = OMXPlayer(my_song)
        print("player initialized")
        player.pause()
        my_volume = player.volume()
        while True:
            if player.position() >= player.duration() - 1.5:
                sleep(0.2)
                commands["skip"] = True
            if commands["play_pause"]:
                if not player.is_playing():
                    sleep(0.2)
                    print("I was paused, now I'm playing")
                    player.play()
                elif player.is_playing():
                    sleep(0.2)
                    player.pause()
                print(player.duration())
                print(player.position())
                commands["play_pause"] = False
            if commands["stop"]:
                sleep(0.2)
                player.stop()
                commands["stop"] = False
            if commands["quieter"]:
                sleep(0.2)
                my_volume = player.volume()
                my_volume = my_volume - 100
                player.set_volume(my_volume)
                print(my_volume)
                commands["quieter"] = False
            if commands["louder"]:
                sleep(0.2)
                my_volume = player.volume()
                if my_volume <= 900:
                    my_volume = my_volume + 100
                player.set_volume(my_volume)
                print(my_volume)
                commands["louder"] = False
            if commands["quit"]:
                sleep(0.2)
                print("run")
                player.quit()
                print("run 2")
                subprocess.check_call(["python", "/home/pi/startup.py"])
                print("run 3")
                break
            if commands["skip"]:
                sleep(0.2)
                player.quit()
                my_song_index = (my_song_index + 1) % my_playlist_length
                if my_song_index == 0:
                    print("my playlist was {}".format(directory))
                    shuffle(directory)
                    print("my playlist is now {}".format(directory))

                my_song = directory[my_song_index]
                player = OMXPlayer(my_song)
                player.set_volume(my_volume)
                commands["skip"] = False

                print("Now, my_song is {}".format(my_song))

    except:
        GPIO.cleanup()
        player.quit()
예제 #10
0
class Player:
    def __init__(self, appli):
        self.currVideo = None
        self.formatId = 0
        self.subtitleId = -1
        self.audioStreamId = 0
        self.omxProcess = None
        self.currTotViewed = 0
        self.lastPos = 0
        self.appli = appli
        self.wasPlaying = False

    def LoadVideo(self, video):
        if self.isStarted():
            self.stop()
        self.wasPlaying = False
        self.currVideo = video
        self.formatId = 0
        self.subtitleId = -1
        self.audioStreamId = 0
        self.currTotViewed = 0
        self.lastPos = 0

    # Set the format of the video
    def setVideoFormat(self, formatId):
        if self.currVideo and formatId != self.formatId:
            # If the video has this format
            if self.currVideo.getFormat(formatId):
                oldFormat = self.formatId
                self.formatId = formatId
                if self.isStarted():
                    self.wasPlaying = False
                    oldPos = self.getPosition()
                    wasPlaying = self.isPlaying()
                    # Try to play the new format but fallback on the previous one if it fails
                    if self.tryPlayingFormat(
                            formatId) or self.tryPlayingFormat(oldFormat):
                        self.setPosition(oldPos)
                        if not wasPlaying:
                            self.playPause()
                    else:
                        return False
                return True
        return False

    # Set a different audio stream
    def setAudioFormat(self, formatId):
        try:
            if self.isStarted():
                if self.omxProcess.select_audio(formatId):
                    self.audioStreamId = formatId
                    return True
                else:
                    return False
            else:
                return False
        except:
            self.clearPlayer()
            return False

    # Set a subtitle track
    def setSubtitlesFormat(self, formatId):
        try:
            if self.isStarted():
                if formatId > -1:
                    self.omxProcess.show_subtitles()
                    if self.omxProcess.select_subtitle(formatId):
                        self.subtitleId = formatId
                        return True
                    else:
                        return False
                else:
                    self.subtitleId = -1
                    return self.omxProcess.hide_subtitles()
            else:
                return False
        except:
            self.clearPlayer()
            return False

    # Tries to play or pause the current video
    def playPause(self):
        if self.currVideo:
            if self.isStarted():
                try:
                    if self.isPlaying():
                        self.omxProcess.pause()
                    else:
                        self.omxProcess.play()
                    return True
                except:
                    self.clearPlayer()
                    return False
            else:
                ok = False
                if self.formatId != 0:
                    ok = self.tryPlayingFormat(self.formatId)
                if not ok:
                    # Try to play formats starting from the highest resolution one
                    for fid in range(1, len(self.currVideo.getFormatList())):
                        if self.tryPlayingFormat(fid):
                            ok = True
                            break
                return ok
        return False

    def stop(self):
        self.wasPlaying = False
        try:
            if self.omxProcess:
                self.omxProcess.quit()
                self.omxProcess = None
                return True
            return False
        except:
            self.clearPlayer()
            return False

    # Tries to play a given format of the video
    def tryPlayingFormat(self, formatId):
        if self.isStarted():
            self.stop()
        try:
            self.formatId = formatId
            print('Trying to play ', formatId, 'path:',
                  self.currVideo.getRessourcePath(formatId))
            self.omxProcess = OMXPlayer(
                self.currVideo.getRessourcePath(formatId), args=['-b'])
            # Wait a bit for loading before disqualifying the format
            while self.omxProcess.playback_status() == 'Paused':
                sleep(0.01)
            if self.isPlaying():
                print('isplaying:True')
                return True
        except Exception as e:
            self.clearPlayer()
            print(str(e), str(self.currVideo.getFormatList()))
        # Handle the case in which the format couldn't be played
        self.stop()
        self.formatId = 0
        return False

    def isPlaying(self):
        try:
            return self.omxProcess and self.omxProcess.is_playing()
        except:
            self.clearPlayer()
            return False

    def isStarted(self):
        try:
            return self.omxProcess and self.omxProcess.can_play()
        except:
            self.clearPlayer()
            return False

    def isPaused(self):
        return self.isStarted() and not self.isPlaying()

    def getPosition(self):
        try:
            if self.isStarted():
                return self.omxProcess.position()
            else:
                return 0
        except:
            self.clearPlayer()
            return 0

    def getDuration(self):
        try:
            if self.isStarted():
                return int(self.omxProcess.duration())
            elif self.currVideo:
                return self.currVideo.duration
            else:
                return 1
        except:
            self.clearPlayer()
            return 1

    def getSubtitles(self):
        subs = {-1: 'None'}
        try:
            if self.isStarted():
                for substr in self.omxProcess.list_subtitles():
                    idx, lng, name, cdc, actv = substr.split(':')
                    subs[idx] = lng + (('-' + name) if len(name) > 0 else '')
                    if actv:
                        self.subtitleId = idx
            return subs
        except:
            self.clearPlayer()
            return subs

    def hasSubtitles(self):
        try:
            return self.isStarted() and len(
                self.omxProcess.list_subtitles()) > 0
        except:
            self.clearPlayer()
            return False

    def getAudioStreams(self):
        auds = {}
        try:
            if self.isStarted():
                for audstr in self.omxProcess.list_audio():
                    idx, lng, name, cdc, actv = audstr.split(':')
                    auds[idx] = lng + (('-' + name) if len(name) > 0 else '')
                    if actv:
                        self.audioStreamId = idx
            return auds
        except:
            self.clearPlayer()
            return auds

    def hasAudioStreams(self):
        try:
            return self.isStarted() and len(self.omxProcess.list_audio()) > 1
        except:
            self.clearPlayer()
            return False

    def hasVideoStreams(self):
        if self.currVideo:
            okFormatList = json.loads(self.currVideo.okFormatsList)
            return len(okFormatList) > 2
        else:
            return False

    def getStatus(self):
        isPlaying = self.isPlaying()
        isPaused = self.isPaused()
        currPos = self.getPosition()
        dur = self.getDuration()
        if isPlaying or isPaused:
            self.wasPlaying = True
            self.currTotViewed += currPos - self.lastPos
            self.lastPos = currPos
            with self.appli.threadLock:
                if self.currTotViewed / dur > Parameters.get().viewedThreshold:
                    self.currVideo.viewed = True
                    self.currVideo.save()
                    self.appli.updatePart('playlist')
        else:
            with self.appli.threadLock:
                pt = Parameters.get().autoRestartPosThresh
            if self.wasPlaying and pt < self.lastPos < self.getDuration() - pt:
                self.tryPlayingFormat(self.formatId)
                self.setPosition(self.lastPos)
        return {
            'position': currPos,
            'duration': dur,
            'isPlaying': isPlaying,
            'isPaused': isPaused
        }

    def setPosition(self, newPos):
        try:
            # If the video is not started, start it and jump to the position
            if self.isStarted() or self.playPause():
                self.omxProcess.set_position(newPos)
                return True
            else:
                return False
        except:
            self.clearPlayer()
            return False

    def getFormatList(self):
        return self.currVideo.getFormatList() if self.currVideo else []

    def getFormatListItems(self):
        return [(fid, f['name']) for fid, f in enumerate(self.getFormatList())]

    def clearPlayer(self):
        if self.omxProcess:
            try:
                self.omxProcess.quit()
            except:
                pass
        self.omxProcess = None
예제 #11
0
class MediaOmxplayerPlugin(MediaPlugin):
    """
    Plugin to control video and media playback using OMXPlayer.

    Requires:

        * **omxplayer** installed on your system (see your distro instructions)
        * **omxplayer-wrapper** (``pip install omxplayer-wrapper``)
    """
    def __init__(self, args=None, *argv, timeout: float = 20., **kwargs):
        """
        :param args: Arguments that will be passed to the OMXPlayer constructor
            (e.g. subtitles, volume, start position, window size etc.) see
            https://github.com/popcornmix/omxplayer#synopsis and
            https://python-omxplayer-wrapper.readthedocs.io/en/latest/omxplayer/#omxplayer.player.OMXPlayer
        :type args: list
        :param timeout: How long the plugin should wait for a video to start upon play request (default: 20 seconds).
        """

        super().__init__(*argv, **kwargs)

        if args is None:
            args = []

        self.args = args
        self.timeout = timeout
        self._player = None
        self._handlers = {e.value: [] for e in PlayerEvent}
        self._play_started = threading.Event()

    @action
    def play(self, resource=None, subtitles=None, *args, **kwargs):
        """
        Play or resume playing a resource.

        :param resource: Resource to play. Supported types:

            * Local files (format: ``file://<path>/<file>``)
            * Remote videos (format: ``https://<url>/<resource>``)
            * YouTube videos (format: ``https://www.youtube.com/watch?v=<id>``)
            * Torrents (format: Magnet links, Torrent URLs or local Torrent files)

        :param subtitles: Subtitles file
        """
        if not resource:
            if not self._player:
                self.logger.warning('No OMXPlayer instances running')
            else:
                self._player.play()

            return self.status()
        else:
            self._play_started.clear()

        self._post_event(MediaPlayRequestEvent, resource=resource)

        if subtitles:
            args += ('--subtitles', subtitles)

        resource = self._get_resource(resource)
        if self._player:
            try:
                self._player.stop()
                self._player = None
            except Exception as e:
                self.logger.exception(e)
                self.logger.warning(
                    'Unable to stop a previously running instance ' +
                    'of OMXPlayer, trying to play anyway')

        from dbus import DBusException

        try:
            from omxplayer import OMXPlayer
            self._player = OMXPlayer(resource, args=self.args)
        except DBusException as e:
            self.logger.warning(
                'DBus connection failed: you will probably not ' +
                'be able to control the media')
            self.logger.exception(e)

        self._post_event(MediaPlayEvent, resource=resource)
        self._init_player_handlers()
        if not self._play_started.wait(timeout=self.timeout):
            self.logger.warning(
                f'The player has not sent a play started event within {self.timeout}'
            )
        return self.status()

    @action
    def pause(self):
        """ Pause the playback """
        if self._player:
            self._player.play_pause()
        return self.status()

    @action
    def stop(self):
        """ Stop the playback (same as quit) """
        return self.quit()

    @action
    def quit(self):
        """ Quit the player """
        from omxplayer.player import OMXPlayerDeadError

        if self._player:
            try:
                try:
                    self._player.stop()
                except Exception as e:
                    self.logger.warning(f'Could not stop player: {str(e)}')

                self._player.quit()
            except OMXPlayerDeadError:
                pass
            finally:
                self._player = None

        return {'status': 'stop'}

    def get_volume(self) -> float:
        """
        :return: The player volume in percentage [0, 100].
        """
        if self._player:
            return self._player.volume() * 100

    @action
    def voldown(self, step=10.0):
        """
        Decrease the volume.

        :param step: Volume decrease step between 0 and 100 (default: 10%).
        :type step: float
        """
        if self._player:
            self.set_volume(max(0, self.get_volume() - step))
        return self.status()

    @action
    def volup(self, step=10.0):
        """
        Increase the volume.

        :param step: Volume increase step between 0 and 100 (default: 10%).
        :type step: float
        """
        if self._player:
            self.set_volume(min(100, self.get_volume() + step))
        return self.status()

    @action
    def back(self, offset=30):
        """ Back by (default: 30) seconds """
        if self._player:
            self._player.seek(-offset)
        return self.status()

    @action
    def forward(self, offset=30):
        """ Forward by (default: 30) seconds """
        if self._player:
            self._player.seek(offset)
        return self.status()

    @action
    def next(self):
        """ Play the next track/video """
        if self._player:
            self._player.stop()

        if self._videos_queue:
            video = self._videos_queue.pop(0)
            self.play(video)

        return self.status()

    @action
    def hide_subtitles(self):
        """ Hide the subtitles """
        if self._player:
            self._player.hide_subtitles()
        return self.status()

    @action
    def hide_video(self):
        """ Hide the video """
        if self._player:
            self._player.hide_video()
        return self.status()

    @action
    def is_playing(self):
        """
        :returns: True if it's playing, False otherwise
        """

        return self._player.is_playing()

    @action
    def load(self, resource, pause=False, **kwargs):
        """
        Load a resource/video in the player.

        :param resource: URL or filename to load
        :type resource: str

        :param pause: If set, load the video in paused mode (default: False)
        :type pause: bool
        """

        if self._player:
            self._player.load(resource, pause=pause)
        return self.status()

    @action
    def metadata(self):
        """ Get the metadata of the current video """
        if self._player:
            return self._player.metadata()
        return self.status()

    @action
    def mute(self):
        """ Mute the player """
        if self._player:
            self._player.mute()
        return self.status()

    @action
    def unmute(self):
        """ Unmute the player """
        if self._player:
            self._player.unmute()
        return self.status()

    @action
    def seek(self, position):
        """
        Seek to the specified number of seconds from the start.

        :param position: Number of seconds from the start
        :type position: float
        """
        if self._player:
            self._player.set_position(position)
        return self.status()

    @action
    def set_position(self, position):
        """
        Seek to the specified number of seconds from the start (same as :meth:`.seek`).

        :param position: Number of seconds from the start
        :type position: float
        """
        return self.seek(position)

    @action
    def set_volume(self, volume):
        """
        Set the volume

        :param volume: Volume value between 0 and 100
        :type volume: float
        """

        if self._player:
            self._player.set_volume(volume / 100)
        return self.status()

    @action
    def status(self):
        """
        Get the current player state.

        :returns: A dictionary containing the current state.

        Format::

            output = {
                "duration": Duration in seconds,
                "filename": Media filename,
                "fullscreen": true or false,
                "mute": true or false,
                "path": Media path
                "pause": true or false,
                "position": Position in seconds
                "seekable": true or false
                "state": play, pause or stop
                "title": Media title
                "url": Media url
                "volume": Volume between 0 and 100
                "volume_max": 100,
            }
        """

        from omxplayer.player import OMXPlayerDeadError
        from dbus import DBusException

        if not self._player:
            return {'state': PlayerState.STOP.value}

        try:
            state = self._player.playback_status().lower()
        except (OMXPlayerDeadError, DBusException) as e:
            self.logger.warning(f'Could not retrieve player status: {e}')
            if isinstance(e, OMXPlayerDeadError):
                self._player = None

            return {'state': PlayerState.STOP.value}

        if state == 'playing':
            state = PlayerState.PLAY.value
        elif state == 'stopped':
            state = PlayerState.STOP.value
        elif state == 'paused':
            state = PlayerState.PAUSE.value

        return {
            'duration':
            self._player.duration(),
            'filename':
            urllib.parse.unquote(self._player.get_source()).split('/')[-1]
            if self._player.get_source().startswith('file://') else None,
            'fullscreen':
            self._player.fullscreen(),
            'mute':
            self._player._is_muted,
            'path':
            self._player.get_source(),
            'pause':
            state == PlayerState.PAUSE.value,
            'position':
            max(0, self._player.position()),
            'seekable':
            self._player.can_seek(),
            'state':
            state,
            'title':
            urllib.parse.unquote(self._player.get_source()).split('/')[-1]
            if self._player.get_source().startswith('file://') else None,
            'url':
            self._player.get_source(),
            'volume':
            self.get_volume(),
            'volume_max':
            100,
        }

    def add_handler(self, event_type, callback):
        if event_type not in self._handlers.keys():
            raise AttributeError(
                '{} is not a valid PlayerEvent type'.format(event_type))

        self._handlers[event_type].append(callback)

    @staticmethod
    def _post_event(evt_type, **evt):
        bus = get_bus()
        bus.post(evt_type(player='local', plugin='media.omxplayer', **evt))

    def on_play(self):
        def _f(player):
            if self.volume and not self._play_started.is_set():
                self.set_volume(self.volume)
            self._play_started.set()

            resource = player.get_source()
            self._post_event(MediaPlayEvent, resource=resource)
            for callback in self._handlers[PlayerEvent.PLAY.value]:
                callback(resource)

        return _f

    def on_pause(self):
        def _f(player):
            resource = player.get_source()
            self._post_event(MediaPauseEvent, resource=resource)
            for callback in self._handlers[PlayerEvent.PAUSE.value]:
                callback(resource)

        return _f

    def on_stop(self):
        def _f(*_, **__):
            self._post_event(MediaStopEvent)
            for callback in self._handlers[PlayerEvent.STOP.value]:
                callback()

        return _f

    def on_seek(self):
        def _f(player, *_, **__):
            self._post_event(MediaSeekEvent, position=player.position())

        return _f

    def _init_player_handlers(self):
        if not self._player:
            return

        self._player.playEvent += self.on_play()
        self._player.pauseEvent += self.on_pause()
        self._player.stopEvent += self.on_stop()
        self._player.exitEvent += self.on_stop()
        self._player.positionEvent += self.on_seek()
        self._player.seekEvent += self.on_seek()

    def toggle_subtitles(self, *args, **kwargs):
        raise NotImplementedError

    def set_subtitles(self, filename, *args, **kwargs):
        raise NotImplementedError

    def remove_subtitles(self, *args, **kwargs):
        raise NotImplementedError
예제 #12
0
class View(QtGui.QMainWindow, gui.Ui_Form):
    
    # Signals
    game = pyqtSignal()

    def __init__(self):
        super(self.__class__, self).__init__()

        self.setupUi(self)

        self.time1.setValue(1)
        self.time2.setValue(1)
        self.time1.setMaximum(1)
        self.time2.setMaximum(1)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.run)
        self.timer.start(1)  # Bei Autostart wirklich 1 ms da kein System im Hintergrund ist

        self.logo.setPixmap(QtGui.QPixmap("/home/pi/Public/bilder/logoS.png"))
        self.logoR.setPixmap(QtGui.QPixmap("/home/pi/Public/bilder/logo.png"))
        self.hintergrund.setPixmap(QtGui.QPixmap("/home/pi/Public/bilder/bg.png"))
        
        
    # Slot
    @pyqtSlot()
    def run(self):
        global mode
        global videoStart
        global explainTextStep
        global startGame
        if mode is 0:  # Savemode
            """
            Hier werden alle Werte zurück gesetzt
            """
            videoStart = True
            setInterrupt(13)
            explainTextStep = 0
            startGame = False
            self.startBildschirm.setVisible(True)
            mode = 1
        elif mode is 1:  # Startbildschirm
            pass
        elif mode is 2:  # Übergang Erklärphase
            removeInterrupt(13)
            setInterrupt(11)            
            self.startBildschirm.setVisible(False)
            self.sensorTexte.setVisible(True)
            mode = 3
        elif mode is 3:  # Erklärphase
            """
            Text anzeigen durch "explainTextStep"
            """
            if explainTextStep is 5:
                if not startGame:
                    startGame = True
                    setInterrupt(13)
                    removeInterrupt(11)
                    self.text.setText("Start Game")
            # Texte Anzeigen lassen
            else:
                self.text.setText(str(explainTextStep))
            pass
        elif mode is 4:  # Übergang Spielphase
            removeInterrupt(11)
            removeInterrupt(13)
            self.sensorTexte.setVisible(False)
            self.startBildschirm.setVisible(False)
            mode = 5
        elif mode is 5:  # Spielphase
            if videoStart:
                self.player = OMXPlayer('/home/pi/Public/Videos/teil1Neu.mp4')        
                self.time1.setMaximum(int(self.player.duration()))
                self.time2.setMaximum(int(self.player.duration()))
                self.player.set_video_pos(260, 300, 1690, 1080)
                videoStart = False
            if self.player.is_playing():                
                restTime = int(self.player.duration())-int(self.player.position())
                self.time1.setValue(restTime)
                self.time2.setValue(restTime)
                pass
                # Spielläuft
            else:
                # Spielfertig
                self.player.quit()
                mode = 0
        else:
            pass
def basic_func():
##        try:
                print(commands)
                print(commands["play_pause"])
                directory = create_playlist()
                shuffle(directory)
                print ("currently, my playlist is {}".format(directory))
                my_playlist_length = len(directory)
                my_song_index = 0
                my_song = directory[0]
                print ("My song right now is {}".format(my_song))
                player = OMXPlayer(my_song)
                print ("im intalized")
                player.pause()
                my_volume = player.volume()
                while True:

                        if player.position() >= player.duration()-1.5:
                                commands["skip"] = True
                        if commands["play_pause"]:
                                print("pressed")
                                if not player.is_playing():
                                    print ("I was paused, now I'm playing")
                                    player.play()
                                elif player.is_playing():
                                    player.pause()    
                                print (player.duration())
                                print (player.position())
                                commands["play_pause"] = False
                        elif commands["quit"]:
                                print ('im quiting')
                                commands["quit"] = False
                                player.quit()
                                break
                        elif commands["quieter"]:
                                my_volume = my_volume-1000
                                player.set_volume(my_volume)
                                print(my_volume)
                                commands["quieter"] = False
                        elif commands["louder"]:
                                my_volume = player.volume()
                                my_volume = my_volume+1000
                                player.set_volume(my_volume)
                                print(my_volume)
                                commands["louder"] = False
                        elif commands["skip"]:
                                player.quit()
                                my_song_index = (my_song_index + 1)%my_playlist_length
                                if my_song_index == 0:
                                        print ("my playlist was {}".format(directory))
                                        shuffle(directory)
                                        print ("my playlist is now {}".format(directory))
        
                                my_song = directory[my_song_index]
                                player = OMXPlayer(my_song)
                                player.set_volume(my_volume)
                                commands["skip"] = False
                                
                                print ("Now, my_song is {}".format(my_song))
                                

                
##        except:
                GPIO.cleanup()
                player.quit()