def play_video(): db = shelve.open('datastore', 'c') video_index = db.get('video_index', 0) videos = db.get('videos', []) if video_index >= len(videos): video_index = 0 if video_index >= len(videos): return db['video_index'] = video_index db.close() print "play " + videos[video_index] videofile = os.path.abspath(os.getcwd()) + "/video/" + videos[video_index] print videofile player = OMXPlayer(videofile, args=['--no-osd', '--no-keys', '-b']) player.play() while 1: try: print player.playback_status() except: print "error end" player.quit() return
def _play_ba(self, ba_path, stop, time_status, save_file): """ function qui lance une bande-annonce dans omx player """ player = OMXPlayer(ba_path, args=['-o', 'hdmi', '-b', '--no-osd']) player.play() # affichage d'un ecran noir pour ne pas voir l'ecran de la ba precedente # brievement avant le changement d'ecran self._display_slide(env_variables.black_image, 1) logging.info("ba: %s, status: %s" % (ba_path, player.playback_status())) # tant que la ba n'est pas fini ou stoppee, on attend while True: try: if player.playback_status() == "Playing" and stop is False and time_status is False: sleep(1) stop = pickle.load(open( save_file, "rb" )) #logging.info("%s, %s, %s" % (player.playback_status(),stop, time_status)) else: logging.warn("before player quit") player.quit() # sortie boucle while break except DBusException: logging.warn("dbus exception") # cette exception est levee a la fin de la ba, sortie du while break return stop
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()
def playAlert(): global done global playOnce done = False playOnce = False if playOnce == False: #pygame.init() #pygame.display.set_mode([100,100]) done = False #print "initialize pygame window" omxp = OMXPlayer(sound_path) omxp.play() print 'Playing Sound' omxp.pause() playOnce = True while True: # for event in pygame.event.get(): # print "for loop getting event" # if event.type == pygame.QUIT: # done = True # print "pygame.QUIT event" # elif event.type == pygame.KEYDOWN: # if event.key == pygame.K_ESCAPE: # done = True # playOnce = False # omxp.quit() #pygame.display.quit() # print "escape key pressed" # elif event.key == pygame.K_F1: # if (omxp.playback_status() == "Playing"): # print(omxp.playback_status()) # elif (omxp.playback_status() == "Paused"): # print(omxp.playback_status()) # elif (omxp.playback_status() == "Stopped"): # print(omxp.playback_status()) # else: # print "Unknown player status, quit player" # playOnce = False # omxp.quit() #pygame.display.quit() if (omxp.playback_status() == "Stopped"): print "alert ended" playOnce = False #done = True omxp.quit() break
def omxplayerRestart(file): global gl_omxplayer try: alpha = int(spinAlpha.get()) except: alpha = 210 if alpha > 255: alpha = 255 elif alpha < 0: alpha = 0 spinAlpha.delete(0, tkinter.END) spinAlpha.insert(0, alpha) # 1. Prüfen, ob omxplayer bereits läuft: if not gl_omxplayer is None: gl_omxplayer.stop() gl_omxplayer.quit() gl_omxplayer = None try: bauwong.update() # DoEvents except: pass # 2. Neue omxplayer-Instanz erstellen und die Wiedergabe der angegebenen Datei starten: playing = False starttim = time.time() # Vergangene Sekunden seit dem 01. Januar 1970 while playing == False: # Diese Schleife ist notwendig, da der omxplayer manchmal # beim Start eines Titels "Zeile 67: <pid> Abgebrochen" meldet. # In diesem Falle würde sofort zum übernächsten Titel gesprungen werden, # was für den unbedarften Benutzer nicht nachvollziehbar ist! gl_omxplayer = OMXPlayer(file, ['--alpha', str(alpha)]) if gl_omxplayer is None: playing = False else: txt = gl_omxplayer.playback_status() playing = txt == "Playing" or txt == "Paused" gl_omxplayer.play() #gl_omxplayer.set_position(0.0) # Sofort mit voller Lautstärke beginnen, kein Fading! # Timeout berücksichtigen: tim = time.time() if tim - starttim >= 2.5: playing = True # Schleife immer verlassen, wenn die Datei nach 2,5s immer noch nicht abgespielt wird time.sleep(0.1) updateButPlayPause()
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
from omxsync import Broadcaster import sys if len(sys.argv) < 2: print('No video specified\nUsage: python test_master.py path/to/video.mp4\n') sys.exit(1) try: print("Load player") player = OMXPlayer(sys.argv[1]) print("Load broadcaster") broadcaster = Broadcaster(player, {'verbose': True}) broadcaster.setup() print("Start playing") player.play() while player.playback_status() != "Stopped": broadcaster.update() print("Stop player") player.stop() print("Exit") except KeyboardInterrupt: player.quit() except Exception as err: print("An error occured:") print(err)
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
omxp.pause() while not done: for event in pygame.event.get(): print "for loop getting event" if event.type == pygame.QUIT: done = True print "pygame.QUIT event" elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: done = True omxp.quit() print "escape key pressed" elif event.key == pygame.K_F1: if (omxp.playback_status() == "Playing"): print(omxp.playback_status()) elif (omxp.playback_status() == "Paused"): print(omxp.playback_status()) elif (omxp.playback_status() == "Stopped"): print(omxp.playback_status()) else: print "Unknown player status, quit player" done = True omxp.quit() keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: print "space pressed" if (omxp.playback_status() == "Stopped"):
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
def run(self): time_status = False stop = False save_file = os.path.join(env_variables.home_ba, 'save.p') pickle.dump(stop, open( save_file, "wb" )) logging.info("in run method") # tant que l'on a pas appuye sur "stopper les ba", on continue ! if self.timer_in_seconds is None: env_variables.lock.acquire() # on joue toutes les bande-annonces une seule fois for track in self.ba_file_list: # sortie de la boucle for si stop = True if stop is True: break # lancement de la ba player = OMXPlayer(track, args=['-o', 'hdmi', '-b', '--no-osd']) player.play() # affichage d'un ecran noir pour ne pas voir l'ecran de la ba precedente # brievement avant le changement d'ecran try: return_code = subprocess.call("export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '" + env_variables.black_image +"'", shell=True) except Exception as e: logging.error('black image display failed: %s' % str(e)) sleep(1) logging.info("ba: %s, status: %s" % (track, player.playback_status())) # tant que la ba n'est pas fini ou stoppee, on attend while True: try: if player.playback_status() == "Playing" and stop is False: sleep(1) stop = pickle.load(open( save_file, "rb" )) #logging.info("%s, %s" % (player.playback_status(),stop)) else: logging.warn("before player quit - timer is None") player.quit() # sortie boucle while break except DBusException: # cette exception est levee a la fin de la ba, sortie du while logging.warn("dbus exception - timer is None") break # affichage du display entre deux bande-annonces # recuperation image correspondante a la ba if stop is False and track != env_variables.ba_carte_fidelite: try: image = track.split('.mp4')[0] + '.jpg' logging.info("slide montre: %s" % image) command = "export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '" + image +"'" return_code = subprocess.call(command, shell=True) if return_code == 0: sleep(env_variables.temps_entre_2_ba) else: raise RuntimeError except Exception as e: logging.error("command is:%s" % command) logging.error("display slide return code: %i" % return_code) logging.error('image display failed: %s' % str(e)) env_variables.lock.release() else: env_variables.lock.acquire() # ajouter un check de la valeur de timer timeout = time.time() + self.timer_in_seconds while stop is False and time_status is False: for track in self.ba_file_list: # sortie de la boucle for si stop = True if stop or time_status: break # lancement de la ba player = OMXPlayer(track, args=['-o', 'hdmi', '-b', '--no-osd']) player.play() # affichage d'un ecran noir pour ne pas voir l'ecran de la ba precedente # brievement avant le changement d'ecran try: return_code = subprocess.call("export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '" + env_variables.black_image +"'", shell=True) except Exception as e: logging.error('black image display failed: %s' % str(e)) sleep(1) logging.info("ba: %s, status: %s" % (track, player.playback_status())) # tant que la ba n'est pas fini ou stoppee, on attend while True: try: if player.playback_status() == "Playing" and stop is False and time_status is False: sleep(1) stop = pickle.load(open( save_file, "rb" )) time_status = time.time() > timeout #logging.info("%s, %s, %s" % (player.playback_status(),stop, time_status)) else: logging.warn("before player quit - timer is set") player.quit() # sortie boucle while break except DBusException: logging.warn("dbus exception - timer is set") # cette exception est levee a la fin de la ba, sortie du while break # affichage du display entre deux bande-annonces # recuperation image correspondante a la ba if stop is False and track != env_variables.ba_carte_fidelite: try: image = track.split('.mp4')[0] + '.jpg' logging.info("slide montre: %s" % image) command = "export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '" + image +"'" return_code = subprocess.call(command, shell=True) if return_code == 0: sleep(env_variables.temps_entre_2_ba) else: raise RuntimeError except Exception as e: logging.error("command is:%s" % command) logging.error("display slide return code: %i" % return_code) logging.error('image display failed: %s' % str(e)) env_variables.lock.release() if time_status is True: subprocess.call(['sudo', 'shutdown', '-h', 'now'])
camera.resolution = (1024, 768) camera.start_preview() camera.annotate_text = "Press red button to post to Twitter" rightbutton.wait_for_press() camera.annotate_text = "" camera.capture(photo_path) camera.stop_preview() photo_tweet(photo_path) sleep(5) while True: #replace with you video, always needs to reestablish variable or won't loop video player = OMXPlayer("test.mov") print("Press the left button to play") rightbutton.when_pressed = player.pause leftbutton.wait_for_press() player.play() print(player.playback_status()) try: while player.playback_status(): if player.playback_status() == "Paused": terrorcam() except: pass print("Waiting for motion") pir.wait_for_motion() tweetpic()
class SpeakerManager: def __init__(self, finishPlayingCallback): # initialize the speaker self.__finishPlayingCallback = finishPlayingCallback self.player = None self.__queue = Queue() self.__interrupt_event = threading.Event() self.__stop_event = threading.Event() self.__worker = SpeakerWorker(logging, self.__queue, self.__stop_event, self.__interrupt_event) self.__worker.start() self.callsCallbackWhenInterrupted = False def deinit(self): self.stop() def stop(self): if self.player is not None or self.isPlaying(): try: self.player.quit() except: pass self.player = None def playAudio(self, path): print("Playing audio file at path {}".format(path)) if self.isPlaying(): self.stop() self.player = OMXPlayer(source=path, args=['-o', 'local']) self.player.stopEvent += lambda event: self.__playingFinished() self.player.play() self.__handle_async(self.__checkPlaying, False) def setVolume(self, volume): pass def isPlaying(self): if self.player is None: return False playing = False try: playing = self.player.playback_status() == "Playing" except: playing = False return playing def __handle_async(self, lfunc, interrupt=True): # ql = self.queue.qsize() if (interrupt == True and not self.__queue.empty() and not self.__interrupt_event.isSet()): self.__interrupt_event.set() self.__queue.put(lfunc) def __checkPlaying(self): interrupt = False # print("checking") while self.isPlaying() and not interrupt: interrupt = self.__interrupt_event.isSet() time.sleep(0.1) # print("checked") if not interrupt or self.callsCallbackWhenInterrupted: self.__playingFinished() def __playingFinished(self): print("SpeakerManager finished playing!") self.stop() self.__finishPlayingCallback()
camera.start_preview() camera.annotate_text = "Press red button to post to Twitter" rightbutton.wait_for_press() camera.annotate_text = "" camera.capture(photo_path) camera.stop_preview() photo_tweet(photo_path) sleep(5) while True: #replace with you video, always needs to reestablish variable or won't loop video player = OMXPlayer("test.mov") print("Press the left button to play") rightbutton.when_pressed = player.pause leftbutton.wait_for_press() player.play() print(player.playback_status()) try: while player.playback_status(): if player.playback_status() == "Paused": terrorcam() except: pass print("Waiting for motion") pir.wait_for_motion() tweetpic()