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 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 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
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 VideoPlayerScreen(Screen): slider = ObjectProperty() minimized = BooleanProperty(False) @staticmethod def clearbckgrnd(): Window.clearcolor = (0, 0, 0, 0) @staticmethod def addbckgrnd(): Window.clearcolor = (0, 0, 0, 1) def play(self): VIDEO_PATH = Path("../videos/20200308tagesthemen.mp4") self.player = OMXPlayer(VIDEO_PATH, args=['-o', 'alsa', '--layer', '10000']) #self.player = OMXPlayer('/home/pi/Documents/Radio/videos/20200223tagesthemen.mp4') self.player.set_video_pos(0, 0, 800, 480) #self.player.hide_video() #self.player.show_video() self.player.set_alpha(100) self.set_slider() #Clock.schedule_once(self.quit, 20) Clock.schedule_interval(self.set_slider, 3) def playpause(self): self.player.play_pause() def quit(self, gg, **kwargs): self.player.quit() App.get_running_app().stop() def set_slider(self, *args): pos = self.player.position() # in seconds as int duration = self.player.duration() # in seconds as float #return pos/duration self.slider.value_normalized = pos / duration #return 0.5 def set_videopos(self, *args): pos = self.player.position() # in seconds as int duration = self.player.duration() # in seconds as float if abs(pos / duration - self.slider.value_normalized) > 0.05: self.player.set_position(self.slider.value_normalized * duration) def change_size(self): # pass #width 800 #height 480 # check if crop as alternative if self.minimized: # self.player.set_video_pos(2,2,798,478) self.player.set_alpha(255) else: # self.player.set_video_pos(2,2,798,418) self.player.set_alpha(100) self.minimized = not self.minimized
class VideoPlayer: def __init__(self, VIDEO_NAME, IMAGE_WIDTH, IMAGE_HEIGHT, USING_VLC=False, audioPlayerRef=None, pygameRef=None): self.USING_VLC = USING_VLC self.VIDEO_FILE = VIDEO_NAME #get a reference to the audio player self.audioPlayerRef = audioPlayerRef self.player = None if self.USING_VLC: if (pygameRef == None): print( "VIDEOPLAYER ERROR: don't have a reference to pygame window!" ) self.vlcInstance = vlc.Instance() #tmp (remove comment here) self.media = self.vlcInstance.media_new('/home/pi/code/' + self.VIDEO_FILE) self.media = self.vlcInstance.media_new(self.VIDEO_FILE) # Create new instance of vlc player self.player = self.vlcInstance.media_player_new() self.player.stop() # Pass pygame window id to vlc player, so it can render its contents there. win_id = pygameRef.display.get_wm_info()['window'] self.player.set_xwindow(win_id) self.player.set_media(self.media) # TODO: correct the line below mouse.move(IMAGE_WIDTH, IMAGE_HEIGHT, True, 0) else: self.omx_stdin = None self.omx_process = None self.tot_sec = None self.STARTED = False self.PAUSED = False if (self.USING_VLC): print("VIDEOPLAYER: using VLC") else: print("VIDEOPLAYER: using OMX") # info about video self.info_video = {} self.chapters = self.get_chapters() self.curr_chapter = 0 print('VIDEOPLAYER: info video \n\t# chapter:{}\n\t{}'.format( len(self.chapters), self.chapters)) def start(self): print("VIDEOPLAYER: Starting video...") self.STARTED = True self.PAUSED = False if self.USING_VLC: self.player.play() else: if self.player: self.player.quit() self.player = None self.player = OMXPlayer(self.VIDEO_FILE, args=['--no-osd']) time.sleep(1) def stop(self): print("VIDEOPLAYER: Stopping video...") self.STARTED = False #TODO: is it necessary #self.PAUSED = True if self.USING_VLC: self.player.stop() else: self.player.quit() self.player = None def pause(self): print("VIDEOPLAYER: Pausing video...") # TODO: add some code here?? #self.PAUSED = True #?? def needUpdate(self): return (self.STARTED and self.player) def update(self): #print("VIDEOPLAYER: update") if self.USING_VLC: if self.player.get_length() - self.player.get_time( ) < 2000 and not self.PAUSED: print("VIDEOPLAYER VLC: a due secondi dalla fine") self.PAUSED = True self.player.set_pause(1) else: if self.player.duration() - self.player.position( ) < 2 and not self.PAUSED: print('VIDEOPLAYER OMX: a due secondi dalla fine') self.PAUSED = True self.player.pause() #self.printStatus() def printStatus(self): print("VIDEOPLAYER: started {}, paused {}".format( self.STARTED, self.PAUSED)) def changeChapter(self, chapter): print("VIDEOPLAYER: change chapter") if chapter != 0: print("VIDEOPLAYER: chapter != 0") # in origin era così riga commentata) #if self.PAUSED == True: #if self.PAUSED == False: #print("VIDEOPLAYER: paused is true") if self.USING_VLC: self.player.set_pause(0) else: if self.player: self.player.play() self.PAUSED = False if self.USING_VLC: self.handle_chapter_vlc(chapter) else: self.handle_chapter_omx(chapter) """ if self.USING_VLC: if self.player.get_length() - self.player.get_time() < 2000 and not self.PAUSED: self.PAUSED = True self.player.set_pause(1) else: if self.player.duration() - self.player.position() < 2 and not self.PAUSED: print('...pausing video') self.PAUSED = True self.player.pause() """ """ #not using language right now # return to italian language if self.audioPlayerRef: self.audioPlayerRef.switchToITA() """ def isPlaying(self): return self.STARTED def switch_language(self): print("Video: switch language...") if self.audioPlayerRef: self.audioPlayerRef.switchLanguage() if self.player: self.player.set_position(0) # get all chapters of video file def get_chapters(self): buff = sp.check_output([ "ffmpeg", "-i", self.VIDEO_FILE, "-f", 'ffmetadata', "file.txt", '-y' ], stderr=sp.STDOUT, universal_newlines=True) #print(buff) self.chapters = [] self.chapters_info = {} names = [] i = 0 for line in iter(buff.splitlines()): m = re.match( r".*Chapter #(\d+:\d+): start (\d+\.\d+), end (\d+\.\d+).*", line) if m != None and m.group(1) not in names: names.append(m.group(1)) self.chapters.append({ "name": i + 1, "start": float(m.group(2)), "end": float(m.group(3)) }) i = i + 1 if len(self.chapters) == 2: self.chapters[len(self.chapters) - 1]['name'] = 3 return self.chapters # check where i am: # 0: before chapter 1 # 1: chapter 1 # 2: chapter 2 # 3: chapter 3 # 10 last chapter def pos2chapter(self, pos): # ~ print('actual position', pos) for x in self.chapters: if pos >= x['start'] / 1000 and pos <= x['end']: return x['name'] if pos < self.chapters[0]['start']: return 0 if pos > self.chapters[len(self.chapters) - 1]['end']: return self.chapters[len(self.chapters) - 1]['name'] # vlc chapter manager def handle_chapter_vlc(self, c): print('VIDEOPLAYER VLC: going to', len(self.chapters), c) if len(self.chapters) == 2: if c == 3: print(1) self.player.set_chapter(1) if c == 1: print(2) self.player.set_chapter(0) else: self.player.set_chapter(c - 1) self.audioPlayerRef.stop() if c == 1: self.audioPlayerRef.start() self.curr_chapter = c # chapter manager def handle_chapter_omx(self, c): self.curr_chapter = self.pos2chapter(self.player.position()) print('VIDEOPLAYER OMX: Handle chapter: from', self.curr_chapter, 'to', c) # ~ if c != curr_chapter and c in [f['name'] for f in chapters]: if c in [f['name'] for f in self.chapters]: cpt = self.chapters[[ y for y, x in enumerate(self.chapters) if x['name'] == c ][0]] time.sleep(1) print('going to', cpt['start']) self.player.set_position(cpt['start']) time.sleep(1) self.audioPlayerRef.stop() if c == 1: self.audioPlayerRef.start() self.curr_chapter = c def kill(self): print("Kill video...") if self.USING_VLC: self.player.stop() else: self.player.quit() self.player = None
# Main ### # Démarre la lecture de la vidéo player = OMXPlayer( video, args=['--no-osd', '-o', 'local', '--loop', '--align', 'center'], dbus_name='org.mpris.MediaPlayer2.omxplayer', pause=True) # Capture les signaux pour arrêter proprement le programme signal.signal(signal.SIGINT, signal_handler) # Singal INT (^c) signal.signal(signal.SIGTERM, signal_handler) # Signal TERM (kill) # Boucle principale pour voir si la lecture est terminée. intro_lock = False led_blink = True while True: led_blink_handler(gpio_led, led_blink) if int(player.position()) == int(player.duration()): player.pause() player.set_position(0.0) player.play() time.sleep(0.5) player.pause() led_blink = True intro_lock = False time.sleep(0.1)
button_thread.start() while running: time.sleep(0.0005) if (current_video == 0): try: button_lock.acquire() # DOM: acquire, not aquire local_button_state = button_state finally: button_lock.release() if ((current_video == 0) and (local_button_state == True)): player.seek(-player.position() + video_timestamps[next_video_to_play] ) #0 + next video in array 10 seconds current_video = next_video_to_play next_video_to_play += 1 if ( next_video_to_play >= number_of_videos ): # -1 number of videos because the last one plays with the sensor state print('revert to default') current_video = 0 next_video_to_play = 1 player.seek(-player.position()) #if the player pos is greater than the video stamp plus the length of the video then revert to default content if (player.position() >= (video_timestamps[current_video] + video_lengths[current_video])):
#!/usr/bin/env python3 from omxplayer.player import OMXPlayer from time import sleep AUDIO_PATH_MLP = "/opt/02_Planets_Part1_Treatment.mlp" AUDIO_PATH_TEST = "/opt/demo_5ch/ChID-BLITS-EBU-Narration441-16b.wav" player = OMXPlayer(AUDIO_PATH_MLP, args=['--layout', '5.1', '-w', '-o', 'hdmi']) seconds = [2, 3, 4, 10] for sec in seconds: sleep(sec) print(player.playback_status()) print(player.position())
class MoviePlayer(metaclass=EventDispatcher): # Evemts MOVIE_STOP_EVENT = "MoviePlayer:Stop" MOVIE_START_EVENT = "MoviePlayer:Start" MOVIE_TRIGER_EVENT = "MoviePlayer:Trigger" MOVIE_PLAY_EVENT = "MoviePlayer:Play" MOVIE_EXIT_EVENT = "MoviePlayer:Exit" player = None isPlaying = False _triggers = [] def __init__(self, volume=4): self.volume = volume def play(self, url, loop=False): self.path = Path(url) self._triggers = [] if (self.player == None): #, '--vol', '0' props = ['--no-osd', '--no-keys'] if (loop): props.append('--loop') self.player = OMXPlayer(self.path, args=props) # self.player.pauseEvent += lambda _: player_log.info("Pause") # self.player.playEvent += lambda _: player_log.info("Play") self.player.exitEvent += lambda _, exit_code: self.handleExit( exit_code) else: self.player.load(self.path) self.isPlaying = True def handleExit(self, eve): self.isPlaying = False self.emit_event(MoviePlayer.MOVIE_EXIT_EVENT) def addTriggers(self, triggers): self._triggers = [] if (len(triggers) > 0): for trigger in triggers: self._triggers.append( Trigger(trigger["time"], trigger["actions"])) def update(self): try: if (self.isPlaying == True and self.player != None and len(self._triggers) > 0 and self.player.is_playing() == True): frame = self.player.position() for t in self._triggers: if (frame >= t.frame): self._triggers.remove(t) self.emit_event(MoviePlayer.MOVIE_TRIGER_EVENT, t.actions) except: pass def pause(self): self.isPlaying = False def stop(self): self.isPlaying = False self._triggers = [] try: self.player.stop() self.player = None except ValueError: print("Oops! That was no valid number. Try again...") def destroy(self): self.player.quit() self.player = None self._triggers = []
try: while player.is_playing() == False: player.play() while GPIO.input( GPIO_PIR ) == 1: #loop while the motion sensor is setting up and still reading high print("Waiting for PIR to settle ...") time.sleep(2) print(" Ready") while True: if int( player.position() ) > player_length: #check once for error here, in case the cue is missed and this overruns the player length empty_mode() motion_sensor_reading = GPIO.input(GPIO_PIR) print("motion detect reading is " + str(motion_sensor_reading)) if motion_sensor_reading == 1: if int(player.position()) < flyaway and int( player.position()) > feeding: flyaway_mode() time.sleep(player_length - empty) #sleep until video runs out, once empty_mode() time.sleep(player_length - empty) #sleep until video runs out, once
# check if chapter button is pressed if VIDEO_STARTED == True and player: chapter = read_buttons() # ~ if not GPIO.input(GPIO_LANG): # ~ time.sleep(1) # ~ switch_language() if chapter > 0: if VIDEO_PAUSED == True: if player: player.play() VIDEO_PAUSED = False print("--- PLAY ---") time.sleep(.3) handle_chapter(chapter) if player.duration() - player.position() < 2 and not VIDEO_PAUSED: VIDEO_PAUSED = True player.pause() # return to italian language AUDIO_NAME = AUDIO_NAME.replace('_eng', '') play_audio_command = 'aplay ' + AUDIO_NAME print('...pausing video') # check if is closed if GPIO.input(GPIO_PIN): sendUDP(b'0') # closed VIDEO_STARTED = False # return to italian language AUDIO_NAME = AUDIO_NAME.replace('_eng', '') play_audio_command = 'aplay ' + AUDIO_NAME print("Stopping video...")
LD_Counter = lostDetectionCounterMax if (LD_Counter): LD_Counter -= 1 print("LD_Counter = %d " % LD_Counter) if _debug else True if (not is_playing): player.set_alpha(100 if _debug else 255) player.play() print("Video has started") is_playing = True else: if (is_playing): print("Video has stopped") player.set_position(0) player.set_alpha(0) position = player.position() time.sleep(0.25) print("player.position()", player.position()) player.pause() is_playing = False # Reset by pressing CTRL + C except KeyboardInterrupt: print("Measurement stopped by User") GPIO.cleanup() logging.debug("Measurement stopped by User") player.quit() except Exception as e: print(e) # logging.debug(e)
class Omx: def __init__(self, media_folder): self.player = None self.media_folder = media_folder self.expects_loading_exit = False self.looping = False def play(self, filename, loop=False): if self.player: self.expects_loading_exit = True self.player.load(filename) else: args = ['-b', '--no-osd', '-o', 'both'] if loop: args += ['--loop'] self.looping = True else: self.looping = False try: self.player = OMXPlayer(filename, args=args) except SystemError as e: print(e) self.player.stopEvent += self.on_player_stop self.player.exitEvent += self.on_player_exit def on_player_stop(self, player): self.player = None def on_player_exit(self, player, exit_status): if self.expects_loading_exit: self.expects_loading_exit = False else: self.player = None def stop(self): if not self.player: return self.player.stop() self.player = None def pause(self): if not self.player: return self.player.play_pause() def seek_fraction(self, fraction): if not self.player: return duration = self.player.duration() self.player.set_position(fraction * duration) def set_volume(self, volume): if not self.player: return if volume > 10: volume = 10 elif volume < 0: volume = 0 self.player.set_volume(volume) def get_source(self): """ Get player source and remove media folder """ source = self.player.get_source() if source.startswith(self.media_folder + "/"): return source[len(self.media_folder) + 1:] else: return source def status(self): if not self.player: return { 'status': 'stopped', 'source': None, } return { 'status': self.player.playback_status(), 'source': self.get_source(), 'position': self.player.position(), 'duration': self.player.duration(), 'volume': self.player.volume(), 'looping': self.looping, }
'--font-size', '100', '--layer', '1', ], dbus_name='org.mpris.MediaPlayer2.omxplayer1') sleep(5) while not done: tock = datetime.now() fileList = listdir('/home/pi/python/videos/chan' + str(currentChanNum)) # slow down checking player position to every 0.1 s to avoid dbus crashing if (tock - checkInterval).total_seconds() > 0.1 and loadingClip == True: try: print('checking player position') playerPosition = player.position() except Exception as e: print(e) handleCrash(False, VIDEO_PATH) # continue checking to see if the main video player has loaded, else mute static player and set loadingClip to False if playerPosition < clipDuration: checkInterval = datetime.now() else: staticPlayer.mute() checkInterval = datetime.now() loadingClip = False staticMuted = True # update individual channel durations. Channels count starting at 1. Clips count from 0. for i in range(1, maxChans + 1):
class PlayerControl: def __init__(self, logger, master, data, subreddit_dic, subreddit_list): self.data = data self.logging = logger self.subreddits = OrderedDict(subreddit_dic) self.subreddits_list = subreddit_list self.curr_subreddit = self.subreddits_list[0] self.playing = False self.paused = False self.spawn_new = False self.alive = False self.last_click = time() - 1 self.delay = 2 self.position = 0 self.root = master self.init_root() self.make_overlay() self.reddit = Reddit(self.data) self.toggle_loading_text() self.subreddits[self.curr_subreddit][2] = self.reddit.get_video_link( self.subreddits[self.curr_subreddit][0], 100) self.toggle_loading_text() self.logging.debug(self.subreddits[self.curr_subreddit][2]) self.play_vid() def init_root(self): self.root.bind("<Escape>", exit) self.root.overrideredirect(True) self.root.wait_visibility(self.root) self.root.wm_attributes("-alpha", 0.0) self.root.geometry("%dx%d+%d+%d" % (800, 480, 0, 0)) def make_overlay(self): self.create_bg() self.create_playback_buttons() self.create_subreddit_buttons() self.create_center_icon() self.create_loading_text() def create_bg(self): img = Image.open('images/background.jpg').resize((800, 480)) self.image = ImageTk.PhotoImage(img) self.panel = tk.Canvas(master=self.root) self.panel.create_image(0, 0, anchor=tk.NW, image=self.image) def create_center_icon(self): button_img = Image.open("images/subreddits/%s.png" % self.curr_subreddit).resize((200, 200)) self.center_icon = ImageTk.PhotoImage(button_img) self.panel.create_image(400, 170, image=self.center_icon) self.root.update() def create_loading_text(self): self.loading_hidden = True self.loading_text = self.panel.create_text( (400, 363), anchor=tk.S, font=('DinosaursAreAlive', 65, 'bold'), text="LOADING..", fill='RoyalBlue1', state=tk.HIDDEN) def toggle_loading_text(self): if self.loading_hidden: self.panel.itemconfig(self.loading_text, state=tk.NORMAL) self.loading_hidden = False else: self.panel.itemconfig(self.loading_text, state=tk.HIDDEN) self.loading_hidden = True self.root.update() def create_playback_buttons(self): self.playback_buttons = {} self.playback_button_photos = {} playback_types = ['next', 'play', 'prev', 'shutdown'] btn_positions = { "next": (800, 240), "play": (400, 480), "prev": (0, 240), "shutdown": (0, 480) } btn_anchors = { "next": tk.E, "play": tk.S, "prev": tk.W, "shutdown": tk.SW } btn_sizes = { "next": (150, 150), "play": (150, 150), "prev": (150, 150), "shutdown": (60, 60) } for playback_type in playback_types: button_img = Image.open("images/playback/%s.png" % playback_type).resize( btn_sizes[playback_type]) self.playback_button_photos[playback_type] = ImageTk.PhotoImage( button_img) self.playback_buttons[playback_type] = self.panel.create_image( btn_positions[playback_type], anchor=btn_anchors[playback_type], image=self.playback_button_photos[playback_type]) self.panel.tag_bind( self.playback_buttons[playback_type], '<Button-1>', getattr(self, '%s_button_func' % playback_type)) self.panel.pack(fill='both', expand='yes') def subreddit_button_event(self, event): x = event.x relative_x = x - 120 index = relative_x // 70 return self.change_subreddit(event, self.current_subreddit_keys[index]) def create_subreddit_buttons(self): self.subreddit_buttons = {} self.subreddit_button_photos = {} x_pos = 120 y_pos = 0 self.current_subreddit_keys = list( filter(lambda x: x != self.curr_subreddit, self.subreddits.keys())) for subreddit_key, _ in self.subreddits.items(): if subreddit_key == self.curr_subreddit: continue x_pos += 5 button_img = Image.open("images/subreddits/%s.png" % subreddit_key).resize((60, 60)) self.subreddit_button_photos[subreddit_key] = ImageTk.PhotoImage( button_img) self.subreddit_buttons[subreddit_key] = self.panel.create_image( x_pos, y_pos, anchor=tk.NW, image=self.subreddit_button_photos[subreddit_key]) self.panel.tag_bind( self.subreddit_buttons[subreddit_key], '<Button-1>', lambda event: self.subreddit_button_event(event)) x_pos += 65 self.root.update() def change_subreddit(self, event, subreddit): self.logging.debug("Change subreddit called to %s" % subreddit) curr_time = time() if curr_time - self.last_click > self.delay: self.last_click = time() if not self.alive: if self.subreddits[subreddit][2] == []: self.curr_subreddit = subreddit self.create_center_icon() self.create_subreddit_buttons() self.paused = False self.position = 0 self.toggle_loading_text() self.subreddits[ self.curr_subreddit][2] = self.reddit.get_video_link( self.subreddits[self.curr_subreddit][0], 100) self.toggle_loading_text() self.play_vid() else: self.curr_subreddit = subreddit self.create_center_icon() self.create_subreddit_buttons() self.paused = False self.position = 0 self.play_vid() def next_button_func(self, event): self.logging.debug("Next Pressed") curr_time = time() if curr_time - self.last_click > self.delay: self.last_click = time() if self.subreddits[self.curr_subreddit][1] < len( self.subreddits[self.curr_subreddit][2]): self.subreddits[self.curr_subreddit][1] += 1 else: self.subreddits[self.curr_subreddit][1] = 0 if self.alive: self.spawn_new = True self.player.stop() else: self.play_vid() def prev_button_func(self, event): self.logging.debug("Prev button func") curr_time = time() if curr_time - self.last_click > self.delay: self.last_click = time() if self.subreddits[self.curr_subreddit][1] > 0: self.subreddits[self.curr_subreddit][1] -= 1 else: self.subreddits[self.curr_subreddit][1] = len( self.subreddits[self.curr_subreddit][2]) - 1 if self.alive: self.spawn_new = True self.player.stop() else: self.play_vid() def play_button_func(self, event): curr_time = time() if curr_time - self.last_click > self.delay: self.last_click = time() self.play_vid() def shutdown_button_func(self, event): self.logging.debug("Shutdown") if not self.playing: self.root.withdraw() if tk.messagebox.askyesno("Shutdown", "Shutdown Moo-ltimedia Player?"): os.system('sudo shutdown -h now') else: self.root.deiconify() def play_vid(self): self.logging.debug("Play button func") self.logging.debug("Playing: {0} Paused: {1}".format( self.playing, self.paused)) self.logging.debug("Current subreddit index: %d" % self.subreddits[self.curr_subreddit][1]) self.logging.debug("Current video URL: %s" % self.subreddits[ self.curr_subreddit][2][self.subreddits[self.curr_subreddit][1]]) if not self.playing: if self.paused: self.player = OMXPlayer( self.subreddits[self.curr_subreddit][2][self.subreddits[ self.curr_subreddit][1]], args=[ '--aspect-mode', 'Letterbox', '--pos', self.position ]) self.paused = False else: self.player = OMXPlayer( self.subreddits[self.curr_subreddit][2][self.subreddits[ self.curr_subreddit][1]], args=['--aspect-mode', 'Letterbox']) self.alive = True self.player.exitEvent += lambda x, y: self.exit_event_func() self.root.update() self.playing = True else: self.paused = True self.playing = False self.position = self.player.position() self.player.stop() def play_vid_after(self, durr): self.logging.debug("Play vid func") self.position = 0 self.root.after(durr, self.play_vid()) def exit_event_func(self): self.logging.debug("Exit event func") self.playing = False self.root.update() if not self.paused: self.position = 0.0 if self.spawn_new: self.spawn_new = False self.play_vid_after(2000) else: self.alive = False def exit_button_func(self): self.logging.debug("Exit button func") if self.alive: self.player.stop() self.root.destroy()
if input_state1 != last_state1: if (not playing and not input_state1): player.set_position(0) player.play() GPIO.output(13, 1) playing = True if playing: if timer > (videoLength - 0.01): print ("Video flie length: %f, Timer: %f" %(videoLength, timer)) timer = 0 player.pause() GPIO.output(13, 0) playing = False else: timer += player.position() / 1000.0 player.exitEvent += lambda _, exit_code: playerExit(exit_code) #GPIO(24) to close omxplayer manually - used during debug if quit_video == True: # pygame.quit() player.quit() os.system('killall omxplayer.bin') playing = False sys.exit(0) os._exit(-1) break #Set last_input states last_state1 = input_state1
for i in range(0, 20): #sleep(2) player.set_position(0) player.pause() player.hide_video() #sleep(2) player.show_video() #player.set_aspect_mode('stretch') #player.set_video_pos(0, 0, 200, 200) player.play() sleep(20) times.append(float("{0:.3f}".format(player.position()))) player.quit() diffs = [] for i in range(len(times) - 1): diff = float("{0:.3f}".format(times[i + 1] - times[i])) diffs.append(abs(diff)) avgdiffs = sum(diffs) / float(len(diffs)) print("times: " + str(times)) print("diffs: " + str(diffs)) print("maxdiff: " + str(max(diffs))) print("avgdiffs:" + str(avgdiffs))
class VideoPlayer: def __init__(self): self.process = None self.cmd = "" self.args = "" self.path = "" self.player = None def composeCommand(self): # split the command and use # the 'glob' module to expand the * wildchar #self.cmd = 'omxplayer --loop --no-osd --win "0 0 {} {}" --crop {},{},{},{} {}'.format(SCREENW, SCREENH, CROPX1, CROPY1, CROPX2, CROPY2, videoFileLocation) self.cmd = 'omxplayer --no-osd' self.args = shlex.split(self.cmd) self.args = self.args[:-1] + glob.glob(self.args[-1]) def loadVideo(self, path): self.path = path print(self.path) #~ self.cmd = 'omxplayer --no-osd {}'.format(videoName) #~ self.args = shlex.split( self.cmd ) #~ self.args = self.args[:-1] + glob.glob( self.args[-1] ) #~ # Open omxplayer #~ try: #~ print( " load the video " ) #~ self.process = Popen( self.args, stdin=PIPE, stdout=PIPE ) #~ print("This is the omxplayer process id: ", self.process.pid ) #~ except: #~ print("something went wrong") #~ quit() def play(self): #~ print("play") if self.player is None: self.player = OMXPlayer(self.path, args=['--no-osd', '--adev', 'local']) #~ self.player.play() #~ self.process.stdin.write(b'i') #~ self.process.stdin.flush() def stop(self): #~ print("stop") if self.player is not None: self.player.quit() self.player = None def pause(self): #~ print("pause") self.player.pause() #self.process.stdin.write(b'p') #self.process.stdin.flush() def kill(self): # quit omxplayer self.player.stop() #~ self.process.stdin.write(b'q') #~ self.process.stdin.flush() #~ self.process.stdin.close() def is_ended(self): if self.player is not None: #~ print(self.player.position()) # ~ if self.player.position() > 10 or self.player.duration() - self.player.position() < 0.2: if self.player.duration() - self.player.position() < 1: return True else: return False def next(self, videoName): self.stop() self.loadVideo(videoName) self.play()
def main(): #print( "main" ) global inputLen, prevInputLen, videoPlayer # Open video player try: print("MAIN: load the video ") videoPlayer = OMXPlayer(PATH_TO_VIDEO_FILE, args=['--no-osd', '--adev', 'local']) #videoPlayer.set_volume( AUDIO_MIN_VOLUME ) #2020-13-07 - we are not using VLC anymore :( # ~ videoPlayer = vlc.MediaPlayer( PATH_TO_VIDEO_FILE ) #process = Popen( args, stdin=PIPE, stdout=PIPE ) #print("This is the omxplayer process id: ", process.pid ) except Exception as exc: print("MAIN: something went wrong in creating the OMX video player {}". format(exc)) quit() #2020-13-07 - we are not a separate thread anymore to check for the actual playhead position #checkPositionThread = threading.Thread(target=checkLength) #checkPositionThread.start() print("MAIN: video length {}".format(videoPlayer.duration())) if B_USE_VIDEO: videoPlayer.set_volume(AUDIO_MIN_VOLUME) # 2020-07-13 - no need to use fullscreen anymore # ~ videoPlayer.toggle_fullscreen() # use it to go fullscreen videoPlayer.play() # initialize Button manager buttonManager = ButtonManager(goToStart_CB, muteAudio_CB, polarity=False) # get the current number of connected input devices inputLen = getInputDevices() prevInputLen = inputLen # start the shutdown handler function. # It will take care of opening and listening on a socket # for a "shutdown message" in order to kill the python process # and shutdown the RaspberryPi shutdownHandlerThread = threading.Thread(target=shutdownHandler) shutdownHandlerThread.start() # Main loop while True: # check if someone plugged in a mouse or a keyboard if (areThereNewInputsDevices()): # if a new input device has been found, tthis very script # must be stopped in order to let space for the user to work # with the Pi, so... # quit video player videoPlayer.stop( ) # will exit current vlc window (desktop will be visible) # TODO: kill all alive thread # find a way to do this # exit the python script quit() else: buttonManager.update() #print("MAIN: position {}".format(position) ) if B_USE_VIDEO: position = videoPlayer.position() if videoPlayer.duration() - position <= 1: videoPlayer.set_position(0.0) time.sleep(0.1)
from omxplayer.player import OMXPlayer from pathlib import Path import time from PIL import Image import os import pygame os.system('xset dpms force off') time.sleep(5) VIDEO_PATH = Path("2.mp4") player = OMXPlayer(VIDEO_PATH) player.can_set_fullscreen() pos = player.position() print(pos) time_end = player.duration() print(time_end) time.sleep(time_end) player.quit() #os.system('xset dpms force off') #os.system('xset dpms force off') time.sleep(5) VIDEO_PATH = Path("1.mp4") player = OMXPlayer(VIDEO_PATH)
# GPIO.add_event_detect(13, GPIO.RISING, bouncetime=300) # GPIO.add_event_detect(21, GPIO.RISING, bouncetime=300) # GPIO.add_event_callback(21, playcb) # GPIO.add_event_callback(13, nextcb) # keyboard setup keyboard.add_hotkey('p', lambda: playcb(21)) keyboard.add_hotkey('n', lambda: nextcb(13)) # start player print('loading ' + videoFile + ' duration ' + str(durations[durationIndex])) player = OMXPlayer(videoFile, args=['--loop'], dbus_name='org.mpris.MediaPlayer2.omxplayer1') sleep(5) print(player.position()) # player.set_aspect_mode('stretch') player.set_position(0.00) # print(player.position()) # player.seek(10) sleep(preroll) # print(player.position()) player.pause() # player.action(16) print('ready') # main try: while True: # check if currently playing clip is ending soon, if yes load next
class VideoPlayer: def __init__(self, root, message_handler, data, name): self.root = root self.message_handler = message_handler self.data = data self.omx_player = None self.name = name self.omx_running = False self.status = 'EMPTY' self.total_length = 0.0 self.bankslot_number = '*-*' self.start = -1.0 self.end = -1.0 self.rate = 1 self.crop_length = 0.0 self.location = '' self.load_attempts = 0 self.alpha = 0 def try_load(self, layer): load_attempts = 0 while (load_attempts < 2): load_attempts = load_attempts + 1 if self.load(layer): print('load success') return True else: print('load failed') self.message_handler.set_message('ERROR', 'failed to load') self.status = 'ERROR' return False def load(self, layer): #try: self.get_context_for_player() is_dev_mode, first_screen_arg, second_screen_arg = self.set_screen_size_for_dev_mode( ) arguments = [ '--no-osd', '--layer', str(layer), '--adev', 'local', '--alpha', '0', first_screen_arg, second_screen_arg ] if not is_dev_mode: arguments.append('--blank=0x{}'.format( self.data.get_background_colour())) self.status = 'LOADING' print('the location is {}'.format(self.location)) if self.location == '': self.status = 'EMPTY' return True self.omx_player = OMXPlayer(self.location, args=arguments, dbus_name=self.name) self.omx_running = True self.total_length = self.omx_player.duration( ) # <-- uneeded once self.duration stores float if (self.end is -1): self.end = self.total_length if (self.start is -1): self.start = 0 self.crop_length = self.end - self.start print('{}: the duration is {}'.format(self.name, self.total_length)) if self.start > 0.9: self.set_position(self.start - 0.9) if 'show' in self.data.settings['sampler']['ON_LOAD']['value']: self.set_alpha_value(255) else: self.set_alpha_value(0) self.pause_at_start() return True #except (ValueError, SystemError) as e: # print(e) #self.message_handler.set_message('ERROR', 'load attempt fail') #return False def pause_at_start(self): position = self.get_position() start_threshold = round(self.start - 0.02, 2) if position > start_threshold: if self.status == 'LOADING': self.status = 'LOADED' self.omx_player.pause() elif self.omx_running: self.root.after(5, self.pause_at_start) def start_video(self): if 'show' in self.data.settings['sampler']['ON_START']['value']: self.set_alpha_value(255) else: self.set_alpha_value(0) if 'play' in self.data.settings['sampler']['ON_START']['value']: self.status = 'PLAYING' self.omx_player.play() else: self.status = 'START' self.pause_at_end() def pause_at_end(self): position = self.get_position() end_threshold = self.end - 0.2 if (position > end_threshold): self.status = 'FINISHED' self.omx_player.pause() print('its paused at end!') elif (self.omx_running): self.root.after(5, self.pause_at_end) def reload(self, layer): self.exit() self.omx_running = False self.try_load(layer) def is_loaded(self): return self.status is 'LOADED' def is_finished(self): return self.status is 'FINISHED' def get_position(self): try: return self.omx_player.position() except: print('{}: error get_position'.format(self.name)) return -1 def get_context_for_player(self): next_context = self.data.get_next_context() self.location = next_context['location'] #self.total_length = next_context['length'] self.start = next_context['start'] self.end = next_context['end'] self.bankslot_number = next_context['bankslot_number'] self.rate = next_context['rate'] def toggle_pause(self): self.omx_player.play_pause() self.status = self.omx_player.playback_status().upper() def toggle_show(self): if self.alpha > 127: self.show_toggle_on = False self.set_alpha_value(0) else: self.show_toggle_on = True self.set_alpha_value(255) def set_alpha_value(self, amount): self.omx_player.set_alpha(amount) self.alpha = amount def seek(self, amount): position = self.get_position() after_seek_position = position + amount if after_seek_position > self.start and after_seek_position < self.end: self.set_position(after_seek_position) #self.player.seek(amount) else: self.message_handler.set_message('INFO', 'can not seek outside range') def change_rate(self, amount): new_rate = self.rate + amount if (new_rate > self.omx_player.minimum_rate() and new_rate < self.omx_player.maximum_rate()): updated_speed = self.omx_player.set_rate(new_rate) self.rate = new_rate print('max rate {} , min rate {} '.format( self.omx_player.maximum_rate(), self.omx_player.minimum_rate())) return new_rate else: self.message_handler.set_message( 'INFO', 'can not set speed outside of range') return self.rate def set_position(self, position): self.omx_player.set_position(position) def exit(self): try: self.omx_player.quit() self.status = 'EMPTY' self.omx_running = False except: pass def set_screen_size_for_dev_mode(self): ## only dev mode is needed now that auto handles all modes... can be removed probably ... if self.data.settings['other']['DEV_MODE_RESET']['value'] == 'on': return True, '--win', '50,350,550,750' else: aspect_mode = self.data.settings['video']['SCREEN_MODE']['value'] return False, '--aspect-mode', aspect_mode
import RPi.GPIO as GPIO #for taking signal from GPIO import subprocess GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(27, GPIO.OUT) GPIO_PIR = 7 VIDEO_PATH = Path("siskin_full.mp4") player = OMXPlayer(VIDEO_PATH) positionEvent = 3 while True: key = input() currtime = player.position() if (currtime > 3): player.seek(-300) print(currtime) if key == 'h': player.seek(300) #player.loop() sleep(5) #player.quit()
class VideoPlayer(object): def __init__(self): self.player = None self.logger = LogObject('Video Player') self.args = ['-b'] self.STATUS_MAP = { 'volume': self._videoVolume, 'length': self._videoLength, 'playback': self._playbackStatus, 'position': self._videoPosition } self.CONTROL_MAP = { 'playpause': self._playPause, 'stop': self._stop, 'mute': self._mute, 'unmute': self._unmute, 'play': self._play, 'pause': self._pause } self.SEEK_MAP = {'relative': self._seek, 'absolute': self._setPosition} def playUrl(self, url): if not self.player: self.player = OMXPlayer(url, args=self.args) else: self.player.load(url) def setVolume(self, volume): self._checkPlayerExist() try: self.player.set_volume(volume) return self.logger.writeAndReturnLog('VOL0003', {'volume': volume}) except (AttributeError, OMXPlayerDeadError): self._raisePlayerError('VOL0004') def sendCommand(self, command): self._checkPlayerExist() try: return self.CONTROL_MAP[command]() except (AttributeError, OMXPlayerDeadError): self._raisePlayerError('CTRL0003') def _stop(self): self.player.quit() return self.logger.writeAndReturnLog('CTRL0004') def _mute(self): self.player.mute() return self.logger.writeAndReturnLog('CTRL0006') def _unmute(self): self.player.unmute() return self.logger.writeAndReturnLog('CTRL0007') def _playPause(self): self.player.play_pause() return self.logger.writeAndReturnLog('CTRL0005') def _play(self): self.player.play() return self.logger.writeAndReturnLog('CTRL0008') def _pause(self): self.player.pause() return self.logger.writeAndReturnLog('CTRL0009') def seek(self, option, time): self._checkPlayerExist() try: return self.SEEK_MAP[option](time) except (AttributeError, OMXPlayerDeadError): self._raisePlayerError('SEEK0007') def _seek(self, seekTime): self.player.seek(seekTime) return self.logger.writeAndReturnLog('SEEK0005', {'position': seekTime}) def _setPosition(self, position): if position > self._videoLength() or position < 0: self._raisePlayerError('SEEK0004', {'position': position}) self.player.set_position(position) return self.logger.writeAndReturnLog('SEEK0006', {'position': position}) def _checkPlayerExist(self): if not self.player: self._raisePlayerError('CTRL0003') def videoStatus(self, status): if not self.player: self._raisePlayerError('STAT0003') try: return self.STATUS_MAP[status]() except (AttributeError, OMXPlayerDeadError): self._raisePlayerError('STAT0003') def _videoPosition(self): return self.player.position() def _videoLength(self): return self.player.duration() def _videoVolume(self): return self.player.volume() def _playbackStatus(self): return self.player.playback_status() def _raisePlayerError(self, logReference, variablesDict={}): returnMsg = self.logger.writeAndReturnLog(logReference, variablesDict) raise PlayerError(returnMsg)
if current_mode == 0: player.play() next_mode = 1 if current_mode == 1: flyin_mode() next_mode = 2 if current_mode == 2: motion_detect_bool = check_motion_sensor(Current_Motion, Previous_Motion) if motion_detect_bool == True: next_mode = 3 elif motion_detect_bool == False: if player.position( ) > flyaway - 2: #loops the feeding mode before flyaway happens feeding_mode() if current_mode == 3: flyaway_mode() next_mode = 4 if current_mode == 4: motion_detect_bool = check_motion_sensor(Current_Motion, Previous_Motion) if motion_detect_bool == True: print("still motioned!") if int(player.position()) > empty + 5: empty_mode() elif motion_detect_bool == False: print("no more motion!")
class VideoPlayerScreen(Screen): slider = ObjectProperty() minimized = BooleanProperty(True) video_path = StringProperty() # 20200308tagesthemen.mp4 def is_playing(self): if hasattr(self, 'player'): try: return self.player.is_playing() except OMXPlayerDeadError: self.leave_player() return False else: return False def set_play_pause_bttn(self, *args): print(self.ids) if self.is_playing(): self.ids.play_pause_image.source = 'atlas://data/images/defaulttheme/media-playback-pause' else: self.ids.play_pause_image.source = 'atlas://data/images/defaulttheme/media-playback-start' def play(self): VIDEO_PATH = Path("videos/" + self.video_path) print(VIDEO_PATH) self.player = OMXPlayer(VIDEO_PATH, args=['-o', 'alsa', '--layer', '100000']) self.player.set_video_pos(0, 0, 800, 480) self.set_slider() self.change_size() Clock.schedule_interval(self.set_slider, 3) Clock.schedule_interval(self.set_play_pause_bttn, 1) def player_stop(self): Clock.unschedule(self.set_play_pause_bttn) Clock.unschedule(self.set_slider) if self.is_playing(): self.player.stop() @staticmethod def leave_player(): App.get_running_app().root.current = 'base' def play_pause(self): self.player.play_pause() def quit(self, gg, **kwargs): self.player.quit() App.get_running_app().stop() def set_slider(self, *args): try: pos = self.player.position() # in seconds as int duration = self.player.duration() # in seconds as float self.slider.value_normalized = pos / duration except OMXPlayerDeadError: self.leave_player() def set_videopos(self, *args): pos = self.player.position() # in seconds as int duration = self.player.duration() # in seconds as float if abs(pos / duration - self.slider.value_normalized) > 0.05: self.player.set_position(self.slider.value_normalized * duration) def change_size(self): if self.minimized: self.player.set_alpha(255) else: self.player.set_alpha(100) self.minimized = not self.minimized
class OmxPlayer(): def __init__(self): self.player = None self.paired = False self.masterIp = None self.audio_volume = 100.0 # omxplayer callbacks def posEvent(self, a, b): print('Position event!' + str(a) + " " + str(b)) # print('Position: ' + str(player.position()) + "s") return def seekEvent(self, a, b): print('seek event! ' + str(b)) return def triggerStart(self, pathToTrack, withPause=False): # lrpi_player#105 # Audio output can be routed through hdmi or the jack, # if settings.json is corrupted, default to the hdmi settings_json = settings.get_settings() output_route = settings_json.get("audio_output") normalised_output_route = 'hdmi' omxArgs = [] if output_route == 'hdmi': normalised_output_route = 'hdmi' omxArgs += ['-w', '--layout', '5.1'] elif output_route == 'jack': normalised_output_route = 'local' omxArgs += ['-o', normalised_output_route] print('OUTPUT: ' + normalised_output_route) print('Full playing args: ' + str(omxArgs)) if not withPause: self.player = OMXPlayer( pathToTrack, args=omxArgs, dbus_name='org.mpris.MediaPlayer2.omxplayer0') sleep(0.25) elif withPause: self.player = OMXPlayer( pathToTrack, args=omxArgs, dbus_name='org.mpris.MediaPlayer2.omxplayer0', pause=True) # Might need to set the volume to 0 a different way, # for some tracks omxplayer plays a short, sharp, shock # before setting the volume to 0 self.player.set_volume(0) sleep(0.5) def primeForStart(self, pathToTrack): self.triggerStart(pathToTrack, withPause=True) def start(self, pathToTrack, syncTimestamp=None, master=False): print("Playing on omx... :", master) print("\n") print(pathToTrack) settings_json = settings.get_settings() volume = settings_json.get("audio_volume") try: if not master: if self.player: self.player.quit() self.player = None if syncTimestamp: pause.until(syncTimestamp) if self.player is None or syncTimestamp is None: self.triggerStart(pathToTrack) self.player.positionEvent += self.posEvent self.player.seekEvent += self.seekEvent # self.player.set_position(0) if volume is not None: self.audio_volume = volume print("Volume set to %s" % self.audio_volume) self.player.set_volume(float(self.audio_volume) / 100.0) print('synctime in omxplayer: ', ctime(syncTimestamp)) if master: self.player.play() return str(self.player.duration()) except Exception as e: print( "ERROR: Could not start player... but audio may still be playing!" ) print("Why: ", e) print("returning position 0...") return str(0) # action 16 is emulated keypress for playPause def playPause(self, syncTimestamp=None): print("Playpausing with syncTimeStamp: ", syncTimestamp) if syncTimestamp: pause.until(syncTimestamp) self.player.action(16) return str(self.player.duration()) def getPosition(self): return self.player.position() def getDuration(self): return str(self.player.duration()) def mute(self): print(self.player.volume()) self.player.mute() def volumeUp(self): print("upper: ", self.player.volume()) self.player.set_volume(self.player.volume() + 0.1) def volumeDown(self, interval): # If we're right at the end of the track, don't try to # lower the volume or else dbus will disconnect and # the server will look at though it's crashed if self.player.duration() - self.player.position() > 1: print("omx downer: ", self.player.volume()) if (self.player.volume() <= 0.07 or interval == 0): return False else: self.player.set_volume(self.player.volume() - ((1.0 / interval) / 4.0)) return True return False def seek(self, position, syncTimestamp=None): if self.player.can_seek(): self.player.set_position(self.player.duration() * (position / 100.0)) return self.player.duration() * (position / 100.0) def status(self, status): if self.player != None: print('status requested from omxplayer!') try: status["source"] = self.player.get_source() status["playerState"] = self.player.playback_status() status["canControl"] = self.player.can_control() status["position"] = self.player.position() status["trackDuration"] = self.player.duration() status["error"] = "" except Exception as e: status["playerState"] = "" status["canControl"] = False status[ "error"] = "Something went wrong with player status request: " + str( e) else: status["playerState"] = "" status["canControl"] = False status["error"] = "Player is not initialized!" status["paired"] = self.paired status["master_ip"] = self.masterIp return status def setPaired(self, val, masterIp): self.paired = val self.masterIp = masterIp print('paired set to: ', val) print('master_ip set to: ', masterIp) def exit(self, syncTimestamp=None): if syncTimestamp: pause.until(syncTimestamp) if self.player: self.player.quit() self.__del__() killOmx() else: return 1 def __del__(self): if self.player: self.player.quit() self.player = None killOmx() print("OMX died")