Ejemplo n.º 1
0
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"
Ejemplo n.º 2
0
def start_video_player(
):  # Starte OMX Videoplayer der am unteren Bildschirmrand angezeigt wird
    # TODO global variablen checken, file_list muss ziemlich sicher nicht global sein,
    #  video_player wahrscheinlich auch nicht, first_time_video_played wird gar nicht benutzt
    global file_list, video_player, index_video, first_time_video_played
    print("Laenge von Filelist: {}".format(len(file_list)))
    t = threading.currentThread()
    index_video = 0
    while getattr(t, "running", True):
        if len(file_list) > 0:
            print("File exists: {}".format(
                os.path.exists(file_list[index_video])))
            if os.path.exists(file_list[index_video]):
                filey = file_list[index_video]
                print("VIDEO Playing {}".format(filey), flush=True)
                t = threading.Event()
                index_video = index_video + 1
                if index_video > len(file_list) - 1:
                    index_video = 0
                try:
                    video_player_playing = video_player.is_playing()
                except:
                    video_player_playing = False

                if not video_player_playing:
                    video_player = OMXPlayer(
                        filey,
                        args=[
                            '--orientation', '270', '--win',
                            '1312,0,1920,1080', '--no-osd', '--vol',
                            '-10000000'
                        ],
                        dbus_name='org.mpris.MeidlaPlayer2.omxplayer1')

                else:
                    video_player.load(filey)

                try:
                    duration_of_video = video_player.duration() + 3
                except:
                    duration_of_video = 3
                    print("duration of video failed", flush=True)

                print(duration_of_video, flush=True)
                video_player.mute()
                if max_people_reached():
                    video_player.hide_video()
                video_player.play_sync()
                sleep(3)
                # sleep(duration_of_video)
            else:
                break
        else:
            break
Ejemplo n.º 3
0
def start_video_player():
    global file_list, video_player, index_video, first_time_video_played
    print("Laenge von Filelist: {}".format(len(file_list)))
    t = threading.currentThread()
    index_video = 0
    while getattr(t, "running", True):
        if len(file_list) > 0:
            print("File exists: {}".format(
                os.path.exists(file_list[index_video])))
            if os.path.exists(file_list[index_video]):
                filey = file_list[index_video]
                print("VIDEO Playing {}".format(filey), flush=True)
                t = threading.Event()
                index_video = index_video + 1
                if index_video > len(file_list) - 1:
                    index_video = 0

                try:
                    video_player_playing = video_player.is_playing()
                except:
                    video_player_playing = False
                print(video_player_playing)
                if not video_player_playing:
                    video_player = OMXPlayer(
                        filey,
                        args=[
                            '--orientation', '270', '--win',
                            '1312,0,1920,1080', '--no-osd', '--vol',
                            '-10000000'
                        ],
                        dbus_name='org.mpris.MeidlaPlayer2.omxplayer1')

                else:
                    video_player.load(filey)

                try:
                    duration_of_video = video_player.duration() + 3
                except:
                    duration_of_video = 3
                    print("duration of video failed", flush=True)

                print(duration_of_video, flush=True)
                video_player.mute()
                if max_people_reached():
                    video_player.hide_video()
                video_player.play_sync()
                sleep(3)
                #sleep(duration_of_video)
            else:
                break
        else:
            break
Ejemplo n.º 4
0
class Player:
    current_player = None # avoid overlapping songs
    status = PlayerStatus.STOPPED

    def __init__(self, id, start_time=0, done_callback=None):
        """
        make a Player (and start playing it)
        """
        Player.status = PlayerStatus.LOADING_DATA

        self.start_time = start_time
        self.done = done_callback
        self.vid_data = VideoData(id, ready_callback=self.play)

        if self.vid_data.unavailable:
            logging.info("{} seems to be unavailable".format(id))
            done_callback()
        elif not self.vid_data.streamable:
            Player.status = PlayerStatus.DOWNLOADING
            # TODO race condition: player could be set to "downloading"
            # after it's already downloaded and playing

    def play(self):
        t = threading.Timer(1.0, self.__play)
        # TODO sketchy solution to the fact that the VideoData can't be accessed
        # by its callback until returns and sets the relevant player variables
        t.start()

    def __play(self):
        logging.info("Starting OMXPlayer for {} at {}".format(self.vid_data.id, self.start_time))

        args = ["-o", "local"]
        if self.start_time != 0:
            args += ["--pos", get_timestamp(self.start_time)]
        if Player.current_volume != 1 and Player.current_volume != 0:
            args += ["--vol", str(linear_to_mbels(Player.current_volume))]

        if Player.current_player is not None:
            Player.current_player.stop()
        Player.current_player = self

        Player.status = PlayerStatus.PLAYING
        self.omx = OMXPlayer(self.vid_data.url, args=args)
        self.omx.exitEvent += lambda p, code: self.stop()

        if self.done:
            self.omx.exitEvent += lambda p, code: self.done()

        self.start_timestamp = time.time() - self.start_time

        if Player.current_volume == 0:
            self.omx.mute()

        logging.info("OMXPlayer for {} has started".format(self.vid_data.id))

    def stop(self):
        if Player.status == PlayerStatus.PLAYING:
            self.omx.quit() # mark player as dead before we block on quitting it
        elif Player.status in (PlayerStatus.DOWNLOADING, PlayerStatus.LOADING_DATA):
            self.vid_data.remove_ready_callback()

        Player.current_player = None
        Player.status = PlayerStatus.STOPPED

    @classmethod
    def stop_current(self):
        if Player.current_player:
            Player.current_player.stop()

    def get_time(self):
        if Player.status == PlayerStatus.PLAYING:
            return time.time() - self.start_timestamp
        else:
            return 0
        # TODO: using player.position() seems cleaner but resulted in resumes
        # ~10 seconds off from the pauses

    current_volume = None
    @classmethod
    def set_volume(cls, vol):
        if Player.current_volume == None or vol != Player.current_volume:
            Player.current_volume = vol

        if Player.current_player and Player.current_player.status == PlayerStatus.PLAYING:
            if vol == 0:
                Player.current_player.omx.mute()
            else:
                Player.current_player.omx.unmute()
                Player.current_player.omx.set_volume(vol)
if not arduino_ports:
    raise IOError("No Arduino found")
if len(arduino_ports) > 1:
    warnings.warn('Multiple Arduinos found - using the first')

print "Connected to Arduino!\n"
ser = serial.Serial(port=arduino_ports[0],timeout=None)

timestamps = [20,99,177,253,334]
duration = 65

VIDEO_PATH = Path("~/vis_display_combined.mp4")
player = OMXPlayer(VIDEO_PATH,args=["--loop","--no-osd"])
#player.set_aspect_mode("stretch")
#player.set_video_pos(0,0,1280,800)
player.mute()
print "Started Video!\n"

try:
    while True:
        message = ser.readline().rstrip().lstrip()
        print message
	if message.startswith('START'):
            id = int(message[5])
            player.set_position(timestamps[id])
            player.unmute()
	if message.startswith('TIMEOUT'):
            player.mute()
	if message.startswith('QUIT'):
            break
except KeyboardInterrupt:
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
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")
Ejemplo n.º 8
0
import signal
import sys
import subprocess

DOOR_TOPIC = 'living_room/doorsensor1'

pi_tv = RpiTV(RPI_HDMI)
pi_player = Rpitify()
pi_tv.turn_off()

url = 'https://www.youtube.com/watch?v=eyU3bRy2x44'
proc = subprocess.Popen(['youtube-dl', '-f', 'best', '-g', url],
                        stdout=subprocess.PIPE)
realurl = proc.stdout.read()
vid_player = OMXPlayer(realurl.decode("utf-8", "strict")[:-1], pause=True)
vid_player.mute()


def door_parser(data):
    if data[0] == 1:
        print("OCCUPIED COMMAND RECVED")
        pi_tv.turn_on()
        #pi_tv.select_source(RPI_HDMI)
        vid_player.play()
        vid_player.mute()
        pi_player.connect()
        pi_player.loadPlaylist('Classy Jazz')
        pi_player.shufflePlaylist()
        pi_player.playPlaylist(0)
        pi_player.setVol(85)
        pi_player.disconnect()