def loop(self): try: end_time = datetime.now() + timedelta(seconds=60) while (datetime.now() < end_time): self.data = self.audioinput() self.fft() if frequency_got == 1000 or frequency_got == -1000: #print("got it") player = OMXPlayer( path + "Hi, I have detected noise levels greater than the average value of 70 to 75 db. This is indicative of Cavitation, which could harm the equipment. I have raised an incident.mp3" ) player.set_volume(1) time.sleep(5) break #self.graphplot() #self.stream.stop_stream() #self.stream.close() except KeyboardInterrupt: self.pa.close() print("End...")
def musicactions(): # if(request.method == 'GET'): s = request.query_string a = dict(item.split("=") for item in s.split("&")) action = a["action"] if (action == "stop"): global player global q if (q != True): print("QUIT") player.quit() q = True elif (action == "play"): global player q = False player = OMXPlayer("file.m4a") print(player) elif (action == "setvolume"): volume = float(a["volume"]) try: player.unmute() if (volume > 50): player.set_volume(450 * volume / 100) elif (volume < 50 and volume > 0): player.set_volume(-100 / (volume / 100)) elif (volume == 0): player.mute() except: #Exception as OMXPlayerDeadError: print("No Player") return "true"
def playVideo(video, player_log): if Path(video.path).is_file(): player = OMXPlayer(video.path, dbus_name='org.mpris.MediaPlayer2.omxplayer1', args=['--loop']) player.playEvent += lambda _: player_log.info("Play") player.pauseEvent += lambda _: player_log.info("Pause") player.stopEvent += lambda _: player_log.info("Stop") player.hide_video() player.set_position(video.start) player.set_volume(video.volume) if video.crop != None: player.set_video_crop(video.crop[0], video.crop[1], video.crop[2], video.crop[3]) player.set_aspect_mode(video.aspect) player.show_video() player.play() return player else: return None
class Music_player(): def __init__(self): self.playing = False self.song = '' self.song_str = '' def play(self, x): self.song_str = x self.song = OMXPlayer(x) self.song.set_volume(-1000) self.playing = True
def initPlayer(self, video, dbusName, log): player = OMXPlayer(video.path, dbus_name=dbusName, args=['--loop']) player.hide_video() player.pause() player.set_position(video.start) player.set_volume(video.volume) player.set_aspect_mode(video.aspect) player.active = False return player
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 Player: player = None playing = False volume = 0.5 file = 'stub.mp3' # file playing files = [] currentNumberFile = 0 def __init__(self): self.totalObject = glob.glob('../*') for item in self.totalObject: if os.path.isdir(item): self.files.append(item) self.files += glob.glob('../*.mp3') self.files += glob.glob('../*.wav') self.countFiles = len(self.files) self.currentNumberFile = 0 if self.playing == False: self.playFile(self.file) def quitPlayer(self): if self.player != None: if self.playing != False: self.playing = False self.player.quit() def playerExit(self, code): self.playing = False self.player = None def playFile(self, fileName): if self.player == None: self.player = OMXPlayer(fileName) self.player.set_volume(self.volume) self.player.exitEvent += lambda _, exit_code: self.playerExit( exit_code) else: self.player.load(fileName) self.playing = True def increseVolume(self): if self.player != None: if self.volume < 1: self.volume += 0.1 self.player.set_volume(self.volume) def decreseVolume(self): if self.player != None: if self.volume > 0: self.volume -= 0.1 self.player.set_volume(self.volume)
FOLDER = '/home/pi/Music/' DBUSNAME = 'org.mpris.MediaPlayer2.omxplayer' ARGS1 = ['-o', 'local', '--no-osd', '--layer', '1', '--loop'] #'--win', '1000,0,1640,480' ARGS2 = ['-o', 'local', '--no-osd', '--layer', '2'] entries = os.listdir(FOLDER) entries.sort() numOfAudios = len(entries) - 1 # this video is used for noise between STANDBY_PATH = Path(FOLDER + "white_noise.mp3") standBy_player = OMXPlayer(STANDBY_PATH, args=ARGS1, dbus_name=DBUSNAME + '1') standBy_player.set_volume(0) RADIO_PATHS = [] for x in range(numOfAudios): RADIO_PATHS.append(Path(FOLDER + entries[x])) NOISE_PATH = Path("/home/pi/Videos/standBy.mp4") #non più lungo di 1 secondo! #initialization of players and video duration players = [] audio_dur = [] something_playing = False noise_playing = False update_audio = False radioRange_steps = 12 # even half_radioRange_steps = radioRange_steps / 2
def object_count(): ## Down_camera.release() ## Front_camera.release() GPIO.output(31, 0) GPIO.output(32, 1) time.sleep(2) GPIO.output(31, 0) GPIO.output(32, 0) print("Object Count Started") end_time = datetime.now() + timedelta(seconds=20) Inventory_count_object = cv2.VideoCapture('/dev/v4l/by-path/platform-3f980000.usb-usb-0:1.2:1.0-video-index0') ## Inventory_count_object.set(3, 480) ## Inventory_count_object.set(4, 320) while datetime.now()< end_time: q=[0,0,0] _, frame = Inventory_count_object.read() if(frame==None): #time.sleep(3) print("frame none") ## player=OMXPlayer(path+"Please find the tools required for.mp3") ## player.set_volume(4) #return 0 hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # hammer low_yellow = np.array([116, 105, 90]) ##100, 130 high_yellow = np.array([130, 255, 255]) red_mask = cv2.inRange(hsv_frame, low_yellow, high_yellow) _, contours, _ = cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=lambda x:cv2.contourArea(x), reverse=True) if len(contours)>0: q[0] = 1 else: q[0] = 0 # wrench low_red = np.array([70, 107, 97]) ##100, 130 high_red = np.array([82, 131, 133]) red_mask = cv2.inRange(hsv_frame, low_red, high_red) _, contours, _ = cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=lambda x:cv2.contourArea(x), reverse=True) if len(contours)>0: q[1] = 1 else: q[1] = 0 low_green = np.array([25, 100, 120]) ##100, 130 high_green = np.array([30, 255, 255]) red_mask = cv2.inRange(hsv_frame, low_green, high_green) _, contours, _ = cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=lambda x:cv2.contourArea(x), reverse=True) if len(contours)>0: q[2] = 1 else: q[2] = 0 print("q ", q) ## cv2.imshow("Frame", frame) ## ## key = cv2.waitKey(1) ## if key == 27: ## break if q[0]==0: print("first one missing") player=OMXPlayer(path+"The hammer is missing from the inventory I will raise an incident.mp3") player.set_volume(1) time.sleep(5) return_value=0 Inventory_count_object.release() print("released") Inventory_count_object = cv2.VideoCapture('/dev/v4l/by-path/platform-3f980000.usb-usb-0:1.2:1.0-video-index0') print("captured again") elif q[0]==1: print("All tools available") return_value=3 player=OMXPlayer(path+"Please find the tools required for the valve repair.mp3") player.set_volume(1) time.sleep(5) Inventory_count_object.release() print("released") Inventory_count_object = cv2.VideoCapture('/dev/v4l/by-path/platform-3f980000.usb-usb-0:1.2:1.0-video-index0') print("captured again") #Inventory_count_object.release() return return_value
def play_voice(): player = OMXPlayer('play.' + audio_type) player.set_volume(100) time.sleep(player.duration() + 1)
flag = 0 Last_RoB_Status = 0 Current_RoB_Status = 0 # this video is used for noise between videos #STANDBY_PATH = Path("/home/pi/Videos/whiteNoise.mp4") STANDBY_PATH = Path("/home/pi/Videos/white_noise.mp4") standBy_player = OMXPlayer( STANDBY_PATH, args=[ '-o', 'local', '--no-osd', '--layer', '1', '--loop', '--win', '1000,0,1640,480' ], dbus_name='org.mpris.MediaPlayer2.omxplayer1') #'--win', '1000,0,1640,480' standBy_player.set_volume(0) #standBy_player.hide_video() #VIDEO_PATHS = [Path("/home/pi/Videos/01.mp4"), Path("/home/pi/Videos/02.mp4"),Path("/home/pi/Videos/03.mp4"), Path("/home/pi/Videos/04.mp4")] VIDEO_PATHS = [ Path("/home/pi/Videos/clip1.mp4"), Path("/home/pi/Videos/clip2.mp4"), Path("/home/pi/Videos/clip3.mp4"), Path("/home/pi/Videos/clip4.mp4"), Path("/home/pi/Videos/clip5.mp4"), Path("/home/pi/Videos/clip6.mp4"), Path("/home/pi/Videos/clip7.mp4"), Path("/home/pi/Videos/clip8.mp4") ] NOISE_PATH = Path("/home/pi/Videos/standBy.mp4") #non più lungo di 1 secondo!
# lcd_string(radio_stations[i], LCD_LINE_1) else: k40.stop() choosing = False # Start playing if not already_playing: kill_radio() try: lcd_string(" Wait...", LCD_LINE_2) radio_player = OMXPlayer(radio_urls[i], args=['-b --vol -2000']) time.sleep(1) radio_player.set_volume(-1000) already_playing = True except Exception, e: print(time.strftime("%d-%m-%y %H:%M")) print(str(e)) print("problem init") kill_radio() lcd_string(" PLEASE RESTART ", LCD_LINE_2) time.sleep(5) f = open('/share/lastplay.txt', 'w') f.write(str(i)) f.close() lcd_string(radio_stations[i], LCD_LINE_1) else: try: lcd_string(" ".join([" PLAY",
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")
# video_kendall_succession = cv2.VideoCapture('video/kendall_succession.mp4') # visuals video_agni_kai = OMXPlayer(Path('video/agnikai.mp4'), dbus_name='org.mpris.MediaPlayer2.omxplayer1', args='--loop') video_agni_kai.pause() video_fire_drill = OMXPlayer(Path('video/fire_drill.mp4'), dbus_name='org.mpris.MediaPlayer2.omxplayer2', args='--loop') video_fire_drill.pause() video_thrones = OMXPlayer(Path('video/thrones.mp4'), dbus_name='org.mpris.MediaPlayer2.omxplayer3', args='--loop') video_thrones.pause() video_agni_kai.set_volume(6) videos = (video_agni_kai, video_fire_drill, video_thrones) curr_player = video_agni_kai curr_player.play() curr_music = office_theme # current audio audio_muted = False music_muted = False while True: # vibration, addr = sock.recvfrom(1024) # vibration = vibration.decode('utf-8')
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)
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, }
class OmxPlayer(BasePlayer): def __init__(self, hplayer, name): super().__init__(hplayer, name) self._validExt = [ 'mp4', 'm4v', 'mkv', 'avi', 'mov', 'flv', 'mpg', 'wmv', '3gp', 'mp3', 'aac', 'wma', 'wav', 'flac', 'aif', 'aiff', 'm4a', 'ogg', 'opus', 'webm', 'jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff' ] self._thread = None self._runflag = threading.Event() self.player = None ############ ## private METHODS ############ # MPV THREAD def _mpv_thread(self): self.emit('player-ready') self.emit('status', self.status()) self.log("player ready") while self.isRunning(): self._runflag.wait(0.37) if self._runflag.isSet(): self.update('time', round(self.player.position(), 2)) time.sleep(0.05) self.isRunning(False) return def _onPlay(self, p): self.update('isPlaying', True) self.update('isPaused', False) self.emit('playing') self._runflag.set() self.log('play') def _onPause(self, p): self.update('isPlaying', False) self.update('isPaused', True) self.emit('paused') self._runflag.clear() self.log('pause') def _onExit(self, p, c): self.player._connection._bus.close() self.player._connection = None self.player = None self._runflag.clear() self.update('isPlaying', False) self.update('isPaused', False) self.emit('end') self.emit('stopped') self.log('stop') ########## ## Inherited "abstract" METHODS overloads ########## # # Start the player: # - instantiate mpv subprocess # - connect IPC socket i/o # def _start(self): # Playback thread self._thread = threading.Thread(target=self._mpv_thread) self._thread.start() # # Exit the player # - stop subprocess # - close IPC socket # def _quit(self): self.isRunning(False) if self._thread: # self.log("stopping process thread") self._thread.join() self.log("stopped") def _play(self, path): self.log("play", path) if self.player: self.player.quit() self.player = OMXPlayer(path, dbus_name='org.mpris.MediaPlayer2.omxplayer2') self.player.playEvent += self._onPlay self.player.pauseEvent += self._onPause # self.player.stopEvent += self._onStop self.player.exitEvent += self._onExit self.player.play() # self.player.set_video_pos(0,0,100,100) # self.update('duration', round(self.player.duration(),2)) def _stop(self): if self.player: self.player.stop() def _pause(self): if self.player: self.player.pause() def _resume(self): if self.player: self.player.play() def _seekTo(self, milli): if self.player: self.player.set_position(milli / 1000) # self.log("seek to", milli/1000) def _skip(self, milli): if self._status['time'] + milli / 1000 < self._status['duration']: if self.player: self.player.seek(milli / 1000) # self.log("skip", milli/1000) def _applyVolume(self, volume): if self.player: self.player.set_volume(volume / 10.0) self.log("VOLUME to", volume)
class PyOmxplayer(EdgeService): # MQTT LOCAL TOPIC CURRENT_VIDEO_CHANGE_TOPIC = "current_video_change_topic" LOCAL_PLAYLIST_READY_TOPIC = "local_playlist_ready_topic" MUTE_TOPIC = "mute_topic" RENDRER_IS_READY_TOPIC = "renderer_is_ready_topic" # PubSub TOPIC LOCAL_MQTT_CONNECTED_TOPIC = "local_mqtt_connected_topic" current_playlist = [] curr_index = -1 player = None mutting = True voltmp = '0' def __int__(self): # ---- EdgeService.__init__(self) # ---- def run(self) -> None: # ---- EdgeService.run(self) # ---- self.subscribe_command(callback=self.update_playlist, topic=self.LOCAL_PLAYLIST_READY_TOPIC) self.subscribe_command(callback=self.mute_player, topic=self.MUTE_TOPIC) self.subscribe_command(callback=self.player_ready_callback, topic=self.LOCAL_MQTT_CONNECTED_TOPIC) # ---- def play_asset(self): if len(self.current_playlist) > 0: asset_id = self.current_playlist[ self.curr_index]["scheduleVideoId"] uri = self.current_playlist[self.curr_index]["uri"] # ---- print("play asset with id:{0} and uri:{1}".format( str(asset_id), str(uri))) # ---- if self.player: self.quitPlayer() # ---- # print("etape 1") # ---- self.voltmp = '0' # ---- if self.mutting: self.voltmp = '-6000' # ---- # print("etape 2") # ---- self.player = OMXPlayer(str(uri), args=[ '-b', '--no-osd', '--no-keys', '--blank=0xFF000000', '--vol', self.voltmp ]) # ---- # print("etape 3") # print(self.player.) # ---- self.player.playEvent += lambda _: print("event Play") self.player.pauseEvent += lambda _: print("event Pause") self.player.stopEvent += lambda _: print("event Stop") self.player.exitEvent += lambda _, __: self.exit_callback() # ---- self.dispatch_event(topic=self.CURRENT_VIDEO_CHANGE_TOPIC, payload=str( self.current_playlist[self.curr_index])) # ---- else: print("no asset to play") # ---- def play_next_asset(self): #print("play next asset") # ---- self.curr_index += 1 # ---- if self.curr_index > len(self.current_playlist) - 1: self.curr_index = 0 # ---- self.play_asset() def play_previous_asset(self): self.curr_index -= 1 # ---- if self.curr_index < 0: self.curr_index = len(self.current_playlist) - 1 # ---- self.play_asset() def idle_rendrer(self): # ---- display loading pass def player_ready_callback(self, payload=None): if len(self.current_playlist) == 0: # ---- self.dispatch_event(topic=self.RENDRER_IS_READY_TOPIC) def mute_player(self, payload=None): # ----- # print("mute player callback") # ----- # self.mutting = bool(int(payload)) # ----- if bool(int(payload)): self.mute() else: self.unmute() def update_playlist(self, payload=None): # ---- #print("update playlist", payload) # ---- data = None try: data = json.loads(payload.decode("utf-8")) except Exception as e: # --- print("{} error: {}".format(self.__class__.__name__, e)) # --- try: data = json.loads(payload) except Exception as e: print("{} error: {}".format(self.__class__.__name__, e)) # ---- # print("data:", data) # ---- tmp_list = data["assets"] # ---- # print("tmp_list: ", tmp_list) # ---- if len(tmp_list) > 0: self.curr_index = -1 self.current_playlist = tmp_list self.play_next_asset() def mute(self): if self.mutting: # print("deja mute") pass else: print("mute") self.mutting = True self.player.set_volume(0) def unmute(self): if self.mutting: #print("unmute") self.mutting = False self.player.set_volume(1) else: #print("deja unmute") pass def exit_callback(self): #print("event Exit ") self.play_next_asset() def quitPlayer(self): #print("quit player") self.player.quit()
DBUSNAME = 'org.mpris.MediaPlayer2.omxplayer' # args for omxplayer ARGS1 = ['-o', 'local', '--no-osd', '--layer', '1', '--loop'] ARGS2 = ['-o', 'local', '--no-osd', '--layer', '2'] #,'--win', '1000,0,1640,480' entries = os.listdir(FOLDER) entries.sort() numOfVideos = len(entries) - 1 # this video is used for noise between STANDBY_PATH = Path(FOLDER + "white_noise.mp4") standBy_player = OMXPlayer(STANDBY_PATH, args=ARGS1, dbus_name=DBUSNAME + '1') standBy_player.set_volume(0) VIDEO_PATHS = [] for x in range(numOfVideos): VIDEO_PATHS.append(Path(FOLDER + entries[x])) NOISE_PATH = Path("/home/pi/Videos/standBy.mp4") #non più lungo di 1 secondo! #initialization of players and video duration players = [] video_dur = [] something_playing = False noise_playing = False update_video = False fade_speed = 10
def Serial_over_WIFI(): s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('192.168.0.10', port)) print "socket binded to %s" % (port) s.listen(1) print "socket is listening" player = OMXPlayer(path + "I am ready.mp3") player.set_volume(1) time.sleep(2) Connection_Status = False c, addr = s.accept() print 'Got connection from', addr c.send('Thank you for connecting\n') player = OMXPlayer(path + "I am connected to the application.mp3") player.set_volume(1) time.sleep(3) #player.play() ## GPIO.output(31, 0) ## GPIO.output(32, 1) ## RGB(0,0,0) while True: recv_data = (c.recv(64)) #print('\x1b[6;30;42m'+ "Recieved data from Device: " +str(recv_data) +'\x1b[0m') print("Recieved data from Device: " + str(recv_data)) if not recv_data: print("Disconnected with device") player = OMXPlayer(path + "I am disconnected from the application.mp3") player.set_volume(1) #player.play() time.sleep(3) ## GPIO.output(31, 1) ## GPIO.output(32, 0) ## RGB(0,0,0) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) c, addr = s.accept() print 'Got connection from', addr c.send('Thank you for connecting\n') player = OMXPlayer(path + "I am connected to the application.mp3") player.set_volume(1) #player.play() time.sleep(3) ## GPIO.output(31, 0) ## GPIO.output(32, 1) if ("Front" in recv_data): ## work=threading.Thread(target=walk_for_thread,args=(3,)) ## work.start() walk_for_thread(2) elif ("Back" in recv_data): ## work=threading.Thread(target=turn_around_updated,args=(5,)) ## work.start() turn_around_updated(5) elif ("Left" in recv_data): ## work=threading.Thread(target=turn_left_updated,args=(2,)) ## work.start() turn_right_updated(0.6) elif ("Right" in recv_data): ## work=threading.Thread(target=turn_right_updated,args=(2,)) ## work.start() turn_left_updated(0.6) elif ("STOP" in recv_data): ## work=threading.Thread(target=walk_stop_for_threading) ## work.start() walk_stop_for_threading() elif ("UpdatesPlease" in recv_data): update_strings = UpdateString_f() c.send(update_strings + "\n") elif ("UCA" in recv_data): ## work=threading.Thread(target=Navigation,args=("UCA",)) ## work.start() ## Navigation("UCA") Navigation("UCA") elif ("UCB" in recv_data): ## work=threading.Thread(target=Navigation,args=("UCB",)) ## work.start() Navigation("UCB") elif ("UCC" in recv_data): ## work=threading.Thread(target=Navigation,args=("UCC",)) ## work.start() Navigation("UCC") ## except: ## sys.exit("systems Exit") c.close()
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)
videos.append(video('../shared/timer.mp4', None, 'fill', 10, 0.35)) player_log = logging.getLogger("Player 1") # Create player 1 player1 = OMXPlayer(videos[0].path, dbus_name='org.mpris.MediaPlayer2.omxplayer1', args=['--loop']) player1.playEvent += lambda _: player_log.info("Play") player1.pauseEvent += lambda _: player_log.info("Pause") player1.stopEvent += lambda _: player_log.info("Stop") player1.pause() player1.hide_video() player1.set_position(videos[0].start) player1.set_volume(videos[0].volume) player1.set_aspect_mode(videos[0].aspect) # Show player 1 player1.show_video() player1.play() sleep(5) # Load player 1 with video 2 player1.pause() player1.hide_video() player1.load(videos[1].path, pause=True) player1.set_position(videos[1].start) player1.set_volume(videos[1].volume) player1.set_aspect_mode(videos[1].aspect)
class PlaybackController(object): def __init__(self): self.player = None self.queue = [] self.current_playbackitem = None self.volume = 0.6 def __str__(self): if self.current_playbackitem: return f"{self.get_status()} {self.current_playbackitem.get_title()}. {len(self.queue)} items in queue." else: return f"{self.get_status()}. {len(self.queue)} items in queue." def get_title(self): if self.current_playbackitem: return self.current_playbackitem.get_title() else: return "Not playing anything." def _on_omxplayer_exit(self, player, exit_status): log.info("OMXPlayer exit: {}".format(exit_status)) self.player = None if exit_status == 0: self.current_playbackitem = None self._new_player() def _new_player(self): """Creates a new player by popping from queue.""" log.info("Creating new OMXplayer.") if self.player is not None: self.player.quit() if self.current_playbackitem is None: if len(self.queue) == 0: raise ValueError("Nothing to play.") else: self.current_playbackitem = self.queue.pop(0) log.info("Creating player for video: {}".format( self.current_playbackitem)) self.player = OMXPlayer(self.current_playbackitem.get_direct_url()) self.player.set_volume(self.volume) self.player.exitEvent.subscribe(self._on_omxplayer_exit) def add_single_url(self, url): n_item = PlaybackItem(url) if n_item is not None: self.queue.append(n_item) return True raise ValueError("Could not get URL") def playlist(self, url): log.info("Adding every videos from playlist to queue.") ydl = youtube_dl.YoutubeDL({ 'logger': log, 'extract_flat': 'in_playlist', 'ignoreerrors': True, }) with ydl: # Downloading youtub-dl infos result = ydl.extract_info(url, download=False) for i in result['entries']: logger.info("queuing video") if i != result['entries'][0]: try: if "://" not in i['url']: self.add_single_url("https://youtube.com/?v=" + i['url']) else: self.add_single_url(i['url']) except Exception as e: log.error("Could not enqueue " + i['url']) log.error(e) def play(self): if self.get_status() == "Playing": log.debug("Playback already playing.") return if self.player is None and len(self.queue) > 0: self._new_player() else: log.error("Nothing to play!") def stop(self): if self.player is not None: self.player.stop() self.player = None def playpause(self): if self.player is None: log.error("No player running.") if len(self.queue) > 0: self.play() else: self.player.play_pause() def pause(self): if self.get_status() == "Paused": log.debug("Playback is already paused.") return def seek(self, seconds): if self.player is None: raise Exception("Player is not running") self.player.seek(seconds) def change_volume(self, increment): self.volume += increment if self.volume < 0.0: self.volume = 0.0 elif self.volume > 1.0: self.volume = 1.0 if self.player is not None: self.player.set_volume(self.volume) def get_volume(self): if self.player is not None: return self.player.volume() else: return self.volume def get_status(self): if self.player is None: return "Stopped" try: return self.player.playback_status() except OMXPlayerDeadError: log.error("OMXPlayer is dead.") self.player = None return "Stopped" def next_video(self): self.stop() self.current_playbackitem = None self._new_player() def shutdown(self): self.stop()