class Gameplay3b(Result): animations = [] animation = None invert = 0 def __init__(self): super(Gameplay3b, self).__init__() self.images = [ Sprite(position=(0, 0), image=load_image("images/things/" + x + ".png")) for x in things ] self.next_state = "GAMEPLAY3a" #for i, thing in enumerate(things): # try: # anim = AnimatedSprite(position=pos[i], images=load_images("images/things/"+thing.lower()+"")) # self.animations.append(anim) # except Exception as e: # self.animations.append(None) # print(e) def startup(self, persistent): self.rt = config.load("positions", "center", [[0, 0], [0, 0], [0, 0]]) self.persist = persistent i = self.persist["choice"] if "choice" in self.persist else 0 self.image = self.images[i] # self.invert = things[i] in ["LUMI", "MURU"] video = "images/things/" + things[i].lower() + ".mp4" if OMXPlayer is not None and os.path.isfile(video): self.player = OMXPlayer(video, args=['--no-osd', '--loop']) else: self.player = None #try: # self.animation = None # gc.collect() # self.animation = AnimatedSprite(position=pos[i], images=load_images("images/things/" + things[i].lower() + "", False)) #except Exception as e: # self.animation = None # print(e) def get_event(self, event): super(Gameplay3b, self).get_event(event) if self.done and self.player is not None: self.player.quit() self.player = None def draw(self, surface): if self.invert: if self.animation is not None: self.animation.draw(surface) self.image.draw(surface) else: self.image.draw(surface) if self.animation is not None: self.animation.draw(surface) def update(self, dt): if self.animation is not None: self.animation.update(dt)
def _show_video(self, video_uri, time_window, touch_enabled, text): pygame.display.flip() t_start = time.time() running = True try: player = OMXPlayer(video_uri) player.set_aspect_mode("stretch") while not player.is_playing(): time.sleep(0.1) except Exception as e: raise Exception("Video not loaded. Error is: " + str(e)) while time.time() - t_start < time_window and running: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN and touch_enabled: running = False player.quit() break try: if not player.is_playing(): running = False except Exception as e: running = False try: if player.is_playing(): player.quit() except Exception as e: pass self._show_black() return {'reaction_time': time.time() - t_start}
class Player: def __init__(self, path, endCallback=None, syncCallback=None): self.finished = False self.path = Path(path) self.syncCallback = syncCallback self.endCallback = endCallback self.musicThread = Thread(target=self.play) self.musicThread.start() def play(self): self.player = OMXPlayer(self.path, args="-o local") self.player.exitEvent = self.exitEvent self.player.stopEvent = self.stopEvent while not self.finished: sleep(0.5) if self.syncCallback and not self.finished: self.syncCallback(self.player.position()) self.player.quit() def stop(self): self.player.quit() def position(self): return self.player.position() def exitEvent(self, player, exit_status): self.finished = True if self.endCallback: self.endCallback() def stopEvent(self, player): self.finished = True if self.endCallback: self.endCallback()
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
def play1(): player = OMXPlayer("speech.mp3") sleep(20) player.quit() player = OMXPlayer("timbre.mp3") sleep(4) player.quit()
class Gameplay3(Result): t = 0.0 def __init__(self): super(Gameplay3, self).__init__() self.image = Sprite(position=(0, 0), image=load_image("images/things/intro.png")) self.next_state = "GAMEPLAY3a" def startup(self, persistent): self.rt = config.load("positions", "center", [[0, 0], [0, 0], [0, 0]]) self.persist = persistent video = "images/things/intro.mp4" if OMXPlayer is not None and os.path.isfile(video): self.player = OMXPlayer(video, args=['--no-osd', '--loop']) else: self.player = None self.t = 0 def update(self, dt): self.t += dt if self.t > 15000: self.done = True def draw(self, surface): self.image.draw(surface) def get_event(self, event): super(Gameplay3, self).get_event(event) if self.done and self.player is not None: self.player.quit() self.player = None
def play(self, audioID: str, saveID: str) -> NoReturn: """ Play a pre-recorded response from the cache, and then copy and resave it with a current audio index number. """ AUDIO_PATH = Path("../data/cache/responses/" + audioID + ".wav") audiolen = TinyTag.get( AUDIO_PATH ).duration # Get the duration of the recording of the reply try: player = OMXPlayer(AUDIO_PATH) # Play the recording # Handle potential errors when the user hasn't set a speech pause amount. # In these cases, no pause pause = float(self.cfg.pause if ( type(self.cfg.pause) is not None) else 0) sleep( audiolen + pause ) # Allow the audio to finish playing before quitting, and add a little leeway except Exception: raise AudioPlaybackError else: subprocess.call( f"cp ../data/cache/responses/{audioID}.wav ../data/cache/responses/{saveID}.wav", shell=True) pass finally: player.quit() # Exit the player
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()
class Radio: def __init__(self): self.stations = [('KPOA', 'https://16693.live.streamtheworld.com/KPOAFM.mp3 '), ('KAZU', 'https://icecastle.csumb.edu/live128'), ('KZSC', 'http://streaming.kzsc.org:8000/kzschigh')] self.station_index = 0 self.play = False self.player = False def __str__(self): state = "" if self.play: state = "on" else: state = "off" return "{} -- {}".format(self.stations[self.station_index][0], state) def get_stations(self): return self.stations def current(self): return self.stations[self.station_index] def next(self): if self.play: self.off() self.station_index = self.station_index + 1 if self.station_index > len(self.stations) - 1: self.station_index = 0 return self.stations[self.station_index] def previous(self): if self.play: self.off() self.station_index = self.station_index - 1 if self.station_index < 0: self.station_index = len(self.stations) - 1 return self.stations[self.station_index] def toggle(self): self.play = not self.play if not self.play: self.off() else: self.on() return self.play def on(self): self.play = True print("playing {}".format(self.stations[self.station_index][0])) self.player = OMXPlayer(self.stations[self.station_index][1]) return self.play def off(self): self.play = False if self.player: print("stopping {}".format(self.stations[self.station_index][0])) self.player.quit() return self.play
def playBGVideo(video, startPos): video_path = VIDEO_PATH + video player_log = logging.getLogger("Stone Player - BG") try: bgPlayer = OMXPlayer(video_path, args=['--loop'], dbus_name='org.mpris.MediaPlayer2.omxplayer0') if bgPlayer.playback_status() == "Playing": return bgPlayer.playEvent += lambda _: player_log.info("Play") bgPlayer.pauseEvent += lambda _: player_log.info("Pause") bgPlayer.stopEvent += lambda _: player_log.info("Stop") # global playbackStatus # playbackStatus = player.playback_status() sleep(5) bgPlayer.set_position(startPos) #seconds from the start of the video # player.pause() # sleep(2) # player.set_aspect_mode('stretch') # player.set_video_pos(0, 0, 200, 200) bgPlayer.play() bgPlayer.quit() except Exception as err: print("bgPlayer ERROR:", str(err))
def main(): if len(sys.argv) < 2: print("Argument is empty") print("Enter path as an argument") sys.exit() logging.info("BEGIN") root = sys.argv[1] jsonf = sys.argv[2] fjson = open(sys.argv[2]) schedule = json.load(fjson) pattern = '*.[mM][pP][44]' file_ext = '.mp4' ff_cmd = '-c:a copy -vcodec copy -y' logging.info("BEGIN") e = k = 0 player1 = OMXPlayer("/home/pi/playout/Logo4.mp4", dbus_name='org.mpris.MediaPlayer2.omxplayer0', args=["-b"]) player2 = OMXPlayer("/home/pi/playout/Logo4.mp4", dbus_name='org.mpris.MediaPlayer2.omxplayer1', args=["-b"]) while True: for prog in schedule["program"]: if prog["source"].find('.mp4') > 5: DUR = duration(prog["source"]) cmd = prog["source"] elif prog["source"].find('41.stream') > 5: DUR = prog["dur"] cmd = prog["stream"] elif prog["source"].find('04.stream') > 5: DUR = prog["dur"] cmd = prog["stream"] #thplay = PlayOutThread(cmd,DUR) if DUR > 3: logging.info("PLAY " + cmd) if (k % 2 == 0): player1 = OMXPlayer( cmd, dbus_name='org.mpris.MediaPlayer2.omxplayer1', args=["-b", "--aspect-mode", "stretch"]) player2.quit() else: player2 = OMXPlayer( cmd, dbus_name='org.mpris.MediaPlayer2.omxplayer2', args=["-b", "--aspect-mode", "stretch"]) player1.quit() sleep(DUR - 0.1) k += 1 else: #print("---------------ERROR") e += 1 logging.error(cmd) logging.info("TOTAL PLAY " + str(k) + " ERROR " + str(e))
def threeD(self): print("3D clicked, ID: " + self.ID) if os.path.isfile('/home/pi/proto/Twin/3D/' + self.ID + '.mp4'): player = OMXPlayer('/home/pi/proto/Twin/3D/' + self.ID + '.mp4') sleep(31) player.quit() else: print("3D 모델을 제공하지 않는 광고입니다.")
def vid(self): print("video clicked, ID: " + self.ID) if os.path.isfile('/home/pi/proto/Twin/vid/' + self.ID + '.mp4'): player = OMXPlayer('/home/pi/proto/Twin/vid/' + self.ID + '.mp4') sleep(31) player.quit() else: print("동영상을 제공하지 않는 광고입니다.")
def vid(self): print("video clicked, ID: " + self.ID) if os.path.isfile('/home/pi/proto/Twin/vid/' + self.ID + '.mp4'): player = OMXPlayer('/home/pi/proto/Twin/vid/' + self.ID + '.mp4') sleep(31) player.quit() else: self.showMessageBox()
def threeD(self): print("3D clicked, ID: " + self.currAD) if os.path.isfile('/home/pi/proto/Twin/3D/' + self.currAD + '.mp4'): player = OMXPlayer('/home/pi/proto/Twin/3D/' + self.currAD + '.mp4') sleep(31) player.quit() else: self.showMessageBox('3D모델')
def play_it(file): try: path = Path(file) player = OMXPlayer(path) sleep(player.duration()) player.quit() sleep(1) except: print('oops all berries') sleep(1)
def playMedia(path="../tests/media/test_media_1.mp4", duration=0, position=0): player = OMXPlayer(path, args=["--no-osd"]) player.set_aspect_mode("fill") if position > 0: player.set_position(position) #player.duration() # this only works if this line is here if duration == 0: duration = player.duration() - position player.play() time.sleep(duration) player.quit()
def 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
def speak(text: str, *, cfg: Config) -> bool: """ Speak error output to the user. This function works very similarly to `VoiceAssistant.speak()`. Returns `True` if the text was successfully spoken, `False` otherwise. """ success = False AUDIO_PATH = Path("../data/tmp/logspeech.wav") DATA_PATH = Path("../data/tmp/data.txt") os.system(f"touch {str(AUDIO_PATH)}") # Create a path for the recording with open("../data/tmp/data.txt", "w") as data: data.write(text) output = int() # Save the reply to a file named using the unique identifer assigned to it # # Command line options (in order of usage): # -v voice # -s speed # -f file to read from (filename.txt) # -w file to save to (filename.wav) # try: espeak_args = f"espeak -v {cfg.voice} -s {str(cfg.speed)} -f {str(DATA_PATH)} -w {str(AUDIO_PATH)}" output = subprocess.call(espeak_args, shell=True) except Exception: print(f"Encoding failed! (code: {output})") raise AudioEncodingError else: print(f"Encoding successful (code: {output})") success = True audiolen = TinyTag.get( AUDIO_PATH).duration # Get the duration of the recording of the reply try: player = OMXPlayer(AUDIO_PATH) # Play the recording # Handle the potential case of `self.cfg.pause` being None pause = float(cfg.pause if type(cfg.pause) is not None else 0) sleep( audiolen + pause ) # Allow the audio to finish playing before quitting, and add a little leeway except Exception: raise AudioPlaybackError finally: player.quit() # Exit the player return success
def _get_length_for_file(self, path): try: temp_player = OMXPlayer(path, args=['--alpha', '0'], dbus_name='t.t') duration = temp_player.duration() temp_player.quit() return duration except Exception as e: print(e) self.message_handler.set_message('INFO', 'cannot load video') return None
def speak(self, text: str, audioID: Optional[str] = None) -> NoReturn: """ Convert text to speech and speak the computer's reply. """ AUDIO_PATH = Path("../data/cache/responses/" + str(audioID) + ".wav") DATA_PATH = Path("../data/tmp/data.txt") os.system( f"touch {str(AUDIO_PATH)}") # Create a path for the recording with open("../data/tmp/data.txt", "w") as data: data.write(text) # Save the reply to a file named using the unique identifer assigned to it # # Command line options (in order of usage): # -v voice # -s speed # -f file to read from (filename.txt) # -w file to save to (filename.wav) # try: espeak_args = f"espeak -v {self.cfg.voice} -s {str(self.cfg.speed)} -f {str(DATA_PATH)} -w {str(AUDIO_PATH)}" output = subprocess.call(espeak_args, shell=True) except Exception: print(f"Encoding failed! (code: {output})") raise AudioEncodingError else: print(f"Encoding successful (code: {output})") audiolen = TinyTag.get( AUDIO_PATH ).duration # Get the duration of the recording of the reply try: player = OMXPlayer(AUDIO_PATH) # Play the recording # Handle potential errors with `self.cfg.pause` being None. pause = float( self.cfg.pause if type(self.cfg.pause) is not None else 0) sleep( audiolen + pause ) # Allow the audio to finish playing before quitting, and add a little leeway except Exception: raise AudioPlaybackError finally: player.quit() # Exit the player if (not self.perms.canSaveToCache) or (audioID is None): # Delete the recording if the user doesn't want recordings to be saved or # if there is no passed in audio index. subprocess.call(f"rm {AUDIO_PATH}", shell=True)
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()
def run(self): omxplayer = OMXPlayer(Path("./video/Slàinte.mp4")) time_remaining = omxplayer.duration() omxplayer_sleep = 1 # one second sleep sessions below for video to run in loop omxplayer.play() while self.running: time_remaining = time_remaining - omxplayer_sleep if time_remaining > 0: sleep(omxplayer_sleep) print('Can Control = '+str(omxplayer.can_control())) # If can_control() = True, pressing Kivy Stop button will make self.running = False and allow # me to take control of this loop and terminate the thread. omxplayer.quit()
def changeVideo(path, win, image): """Show sub video by using Omxplayer :param path: path to the video :param win: window name :param image: last video frame """ player_one = OMXPlayer(path) time.sleep(2.5) cv2.imshow(win, image) cv2.waitKey(25) player_one.quit()
class Player(object): def __init__(self, media_dir): self.media_dir = media_dir self.player = None self.subtitles = True def play(self, filename): if self.player: self.player.quit() self.player = None video_path = Path(self.media_dir + filename) self.player = OMXPlayer(video_path, args=['--no-osd']) def quit(self): self.player.quit() self.player = None def pause(self): self.player.play_pause() def seek(self, val): self.player.set_position(val) def set_volume(self, val): self.player.set_volume(val) def toggle_subtitles(self): if self.subtitles: self.player.hide_subtitles() else: self.player.show_subtitles() self.subtitles = not self.subtitles def set_subtitle_track(self, val): self.player.select_subtitle(val) @property def status(self): if self.player != None: return { 'time': int(self.player.position()), 'length': int(self.player.duration()), 'volume': int(self.player.volume()), 'subtitle_tracks': self.player.list_subtitles() } return {'time': 0, 'length': 0, 'volume': 0, 'subtitle_tracks': []}
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()
def on_message(client, userdata, msg): try: print("Received song request: " + msg.payload) r = requests.get( "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=" + msg.payload + "&key=AIzaSyCudOMcwOsl-EGRHCyK5tWgwY6tWWsYs1o") video_id = r.json() video = pafy.new(str(video_id['items'][0]['id']['videoId'])) bestaudio = video.getbestaudio() print("Starting player") player = OMXPlayer(bestaudio.url) print("Playing now!") time.sleep(15) player.quit() print("Song Finished") except: print("An error occured") client.publish("get_song", "New song please!")
def play_video(): global config # get the global config object print("starting presentation") # omxplayer -o hdmi _-eQ_8F4nzyiw.mp4 --win '0 0 1920 1080' --loop width = config['SCREEN CONF']['Width'] height = config['SCREEN CONF']['Height'] video_to_play = config['SCREEN CONF']['current video'] print("File to play:", video_to_play) # see if the video is real if not os.path.isfile(video_to_play): thereIsNewVid, filename = check_for_new() get_video(filename) video_to_play = config['SCREEN CONF']['current video'] try: # start the player player = OMXPlayer( video_to_play, args=['--win', '0 0 %s %s' % (width, height), '--loop']) except Exception as e: print('play_video, omxplayer:', e) # quirie the server thereIsNewVid, filename = check_for_new() if thereIsNewVid: done = get_video(filename) # get the new video get_video(filename) while True: thereIsNewVid, filename = check_for_new() if thereIsNewVid: done = get_video(filename) # get the new video player.quit() video_to_play = filename player = OMXPlayer( video_to_play, args=['--win', '0 0 %s %s' % (width, height), '--loop']) print("File to play:", video_to_play) check_for_settings_change() # check the server for updated settings tv_control() # use the CEC connection to setup a schedule time.sleep(int(config['SERVER CONF']['update interval (seconds)']))
def __init__(self): #loading settings from setup.config settings = sl_settings.Settings() if not settings.load(): error(1) ip_setup = dynamic_ip() ip_setup.set(settings.get("ip_address")) plr = OMXPlayer(settings.get("file_name"),["--blank","--no-osd"]) if settings.get("ismaster") == "True": if ip_setup.waitForConnections(settings.get("num_clients")): ip_setup.sendStartSignal() else: ip_setup.connectToServer() ip_setup.waitForStartSignal() print "this function is not ready yet" ### TODO: error check #loop_time = plr.duration() - float(settings.get("load_time")) plr.play() while True: try: if settings.get("ismaster") == "False": ip_setup.waitForStartSignal() plr.set_position(0) elif settings.get("ismaster") == "True": sleep(plr.duration() - 1.0) #sleep(6) ip_setup.sendStartSignal() plr.set_position(0) except KeyboardInterrupt: print "interrupted!" ip_setup.closeConnection() ip_setup.setOldIp() plr.stop() plr.quit() break #plr.stop() ip_setup.setOldIp()
def video_loop(master): video_count = 0 width = master.winfo_screenwidth() height = master.winfo_screenheight() while True: VIDEO_PATH = Path(my_videos[video_count]) player = OMXPlayer(VIDEO_PATH) player.set_video_pos(width * 0.162, height * 0.147, width * 0.674, height * 0.833) player.set_aspect_mode('fill') sleep(player.duration()) player.quit() video_count = video_count + 1 if video_count < len( my_videos) - 1 else 0
def __omxplay(audiofile: str, pause: float) -> int: """ Play audio using `omxplayer`. Raises `extensions.AudioPlaybackError` upon failure. """ audiolen = TinyTag.get( audiofile).duration # Get the duration of the recording of the reply try: player = OMXPlayer(audiofile) # Play the recording # Handle potential errors with the pause being None. full_pause = audiolen + float(pause if type(pause) is not None else 0) sleep( full_pause ) # Allow the audio to finish playing before quitting, and add a little leeway except Exception: raise AudioPlaybackError finally: player.quit() # Exit the player
VIDEO_PATH_OPENING = Path("./assets/opening.mp4") VIDEO_PATH_BATTLE = Path("./assets/battle-test.mp4") player_opening = OMXPlayer(VIDEO_PATH_OPENING, args=['--no-osd'], pause=True) #player_battle = OMXPlayer(VIDEO_PATH_BATTLE) #player_battle.pause() sleep(5) player_opening.play() sleep(3) player_opening.stop() player_opening.quit() print("quit opening player") #sleep(3) #print("creating new player instance for the battle") #player_battle = OMXPlayer(VIDEO_PATH_BATTLE) #sleep(5) #player_battle.stop() #sleep(3) #player_opening.quit()
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()