Example #1
0
class Player:
    def __init__(self, url):
        self.url = url
        self.player = None
        self.state = True
        self.playlist = False
        self._play = True

    def start(self):
        if isinstance(self.url, string_types):
            cmd = 'youtube-dl -g -f best {0}'.format(self.url)
            yt_dl = subprocess.Popen(cmd,
                                     shell=True,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
            (url, err) = yt_dl.communicate()
            if yt_dl.returncode != 0:
                sys.stderr.write(err)
                print('error')
            yurl = url.decode('UTF-8').strip()
            self.player = OMXPlayer(yurl, args=['-o', 'hdmi'])
            return self.player.duration()

    def stop(self):
        self.player.stop()
        self._play = False
        self.player = None
        return False

    def skip(self):
        if self.playlist == True:
            self.player.stop()
            return True
        else:
            self.player.stop()
            return False

    def toggle(self):
        #false = not playing // true = playing
        if self.state == True:
            self.state = False
            self.player.pause()
        elif self.state == False:
            self.state = True
            self.player.play()
        else:
            return False

    def is_play(self):
        return self.player.can_control()
Example #2
0
  def run(self):
    omxplayer = OMXPlayer(Path("./video/SlĂ inte.mp4"))
    time_remaining = omxplayer.duration()
    omxplayer_sleep = 1 # one second sleep sessions below for video to run in loop
    omxplayer.play()
    while self.running:
        time_remaining = time_remaining - omxplayer_sleep
        if time_remaining > 0:
            sleep(omxplayer_sleep)
        print('Can Control = '+str(omxplayer.can_control())) 
        # If can_control() = True, pressing Kivy Stop button will make self.running = False and allow
        # me to take control of this loop and terminate the thread.

    omxplayer.quit()
Example #3
0
# 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
        sleep(0.5)
        # try-except because it happens that this is executed when clips are reloading and no player instance present
        try:
            if player.can_control():
                if player.position() > (durations[durationIndex] - 1):
                    print('auto next after playback')
                    nextcb(0)
        except:
            print('.')
        # do nothing
        pass


# cleanup
except KeyboardInterrupt:
    # GPIO.cleanup()       # clean up GPIO on CTRL+C exit
    player.quit()
Example #4
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")