Exemplo n.º 1
0
def play_video():
    global player

    if switch_SD_HD.is_pressed:  # Switch is in the 'SD' position
        led.color = Color('gold')

        if player is not None:
            player.stop()
            sleep(0.5)

        command = ['/usr/bin/tvservice -c "PAL 4:3"']
        subprocess.call(command, shell=True)
        sleep(0.5)
        VIDEO_PATH = Path("/video/SD_DemoVideo.mp4")
        player = OMXPlayer(VIDEO_PATH,
                           args=['--no-osd', '--no-keys', '--blank', '--loop'])

    else:
        led.color = Color('green')

        if player is not None:  # i.e. first run
            player.stop()
            sleep(0.5)
            command = [
                '/usr/bin/tvservice -p'
            ]  # not needed on first run as output defaults to HDMI as HDMI connector is always present in demo box
            subprocess.call(command, shell=True)
            sleep(0.5)

        VIDEO_PATH = Path("/video/HD_DemoVideo.mp4")
        player = OMXPlayer(VIDEO_PATH,
                           args=['--no-osd', '--no-keys', '--blank', '--loop'])
Exemplo n.º 2
0
class Video_Player:
    def __init__(self, player_id, video_path):
        self.player_id = player_id
        self.video_path = video_path
        self.player = OMXPlayer(video_path,
                                args=['--loop'],
                                dbus_name="org.mpris.MediaPlayer2.player" +
                                player_id)
        sleep(2)

    #

    def load(self, video_path):
        self.player.hide_video()
        self.video_path = video_path
        self.player.load(video_path)

    def play(self):
        self.player.play()
        self.player.show_video()

    def pause(self):
        self.player.hide_video()
        self.player.pause()

    def stop(self):
        self.player.stop()
Exemplo n.º 3
0
def playVideos(vN):

    global playing
    global player
    global player1
    global first

    print("Dentro funcion video >> " + str(vN))
    vid = "/home/pi/Desktop/videocoto/videos/" + str(vN) + ".mp4"
    print("Toca reproducir ahora: " + vid)

    if playing == 0:
        print("Not Playing: " + str(playing))

        VIDEO_PATH = Path(vid)
        if slave == False:
            player = OMXPlayer(VIDEO_PATH, args=omx_arg, dbus_name=bus[0])

        if slave == True:
            player = OMXPlayer(VIDEO_PATH,
                               args=omx_arg_pasive,
                               dbus_name=bus[0])

        player.seek(0)
        player.play()

        if first == 1:
            player1.stop()

        first = 1
        playing = 1

    elif playing == 1:
        print("Is Playing: " + str(playing))

        VIDEO_PATH = Path(vid)
        if slave == False:
            player1 = OMXPlayer(VIDEO_PATH, args=omx_arg, dbus_name=bus[1])

        if slave == True:
            player1 = OMXPlayer(VIDEO_PATH,
                                args=omx_arg_pasive,
                                dbus_name=bus[1])

        player1.seek(0)
        player1.play()

        player.stop()
        playing = 0
Exemplo n.º 4
0
	def __init__(self):
		#loading settings from setup.config
		settings = sl_settings.Settings()
		if not settings.load():
			error(1)

		ip_setup = dynamic_ip()
		ip_setup.set(settings.get("ip_address"))
	
		plr = OMXPlayer(settings.get("file_name"),["--blank","--no-osd"])

		if settings.get("ismaster") == "True":
			if ip_setup.waitForConnections(settings.get("num_clients")):
				ip_setup.sendStartSignal()
		else:
			ip_setup.connectToServer()
			ip_setup.waitForStartSignal()
			print "this function is not ready yet"
			### TODO: error check 
		#loop_time = plr.duration() - float(settings.get("load_time"))
		plr.play()
	
		while True:
			try:
				if settings.get("ismaster") == "False":
					ip_setup.waitForStartSignal()
					plr.set_position(0)
				elif settings.get("ismaster") == "True":
					sleep(plr.duration() - 1.0)
					#sleep(6)
					ip_setup.sendStartSignal()
					plr.set_position(0)
			except KeyboardInterrupt:
				print "interrupted!"
				ip_setup.closeConnection()
				ip_setup.setOldIp()
				plr.stop()
				plr.quit()
				break
		#plr.stop()

		ip_setup.setOldIp()
Exemplo n.º 5
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()
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()
Exemplo n.º 7
0
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
Exemplo n.º 8
0
player.set_video_pos(0, 0, 700, int(512 * 2.14))
sleep(10)

if noCommMode:
    # for debugging
    player.set_position(120 * 60)
    #    player.play()
    #    sleep(1)
    #    player.pause()
    sleep(20)
    player.set_position(130 * 60)
    #    player.play()
    sleep(20)
    player.set_position(140 * 60)
    sleep(20)
    player.stop()

else:
    while True:
        data = conn.recv(1024)
        print('received: ' + str(data))
        if data == 'term':
            break
        if '_' in data:
            cmd = data.split('_')[0]
            arg = float(data.split('_')[1])
            if cmd == 'pause':
                player.set_position(arg)
                player.play()
                sleep(10)
                player.pause()
Exemplo n.º 9
0
class ScreenMovie(LcarsScreen):
    def setup(self, all_sprites):
        ############ Start base screen #############

        ### BASE_ui

        all_sprites.add(LcarsBackgroundImage(), layer=0)
        self.ui_screen_base = all_sprites.get_sprites_from_layer(0)

        all_sprites.add(LcarsTab(colours.COM2, 3, (50, 80)), layer=1)
        all_sprites.add(LcarsImageBlock(colours.BLUE5,
                                        pos=(50, 115),
                                        rectSize=(1688, 38)),
                        layer=1)
        all_sprites.add(LcarsTab(colours.COM2, 4, (50, 1810)), layer=1)

        all_sprites.add(LcarsTab(colours.COM2, 1, (953, 50)), layer=1)
        all_sprites.add(LcarsImageBlock(colours.BLUE5,
                                        pos=(953, 1361),
                                        rectSize=(443, 77)),
                        layer=1)
        all_sprites.add(LcarsBlockSmall(
            colours.BLUE6, (953, 116),
            "REWIND",
            self.rewHandler,
            textSize=.75,
            fontFace="assets/OpenSansCondensed-Bold.ttf"),
                        layer=2)
        all_sprites.add(LcarsBlockSmall(
            colours.BLUE6, (953, 365),
            "PLAY",
            self.playHandler,
            textSize=.75,
            fontFace="assets/OpenSansCondensed-Bold.ttf"),
                        layer=2)
        all_sprites.add(LcarsBlockSmall(
            colours.BLUE6, (953, 614),
            "F F",
            self.ffHandler,
            textSize=.75,
            fontFace="assets/OpenSansCondensed-Bold.ttf"),
                        layer=2)
        all_sprites.add(LcarsBlockSmall(
            colours.BLUE6, (953, 863),
            "STOP",
            self.stopHandler,
            textSize=.75,
            fontFace="assets/OpenSansCondensed-Bold.ttf"),
                        layer=2)
        all_sprites.add(LcarsBlockSmall(
            colours.BLUE6, (953, 1112),
            "BASE",
            self.mainHandler,
            textSize=.75,
            fontFace="assets/OpenSansCondensed-Bold.ttf"),
                        layer=2)
        all_sprites.add(LcarsImageBlock(colours.BLUE5,
                                        pos=(953, 1361),
                                        rectSize=(443, 77)),
                        layer=1)
        all_sprites.add(LcarsTab(colours.COM2, 2, (953, 1810)), layer=1)

        self.fileList = LcarsTextBlock(colours.BLUE6, (94, 365),
                                       self.dirlist(),
                                       rectSize=(1694, 781))
        all_sprites.add(self.fileList, layer=3)
        all_sprites.add(LcarsImageBlock(colours.BLUE2,
                                        pos=(94, 116),
                                        text="01-3906",
                                        rectSize=(243, 100)),
                        layer=3)
        all_sprites.add(LcarsImageBlock(colours.BLUE3,
                                        pos=(200, 116),
                                        text="96-4783",
                                        rectSize=(243, 500)),
                        layer=3)
        all_sprites.add(LcarsImageBlock(colours.BLUE4,
                                        pos=(706, 116),
                                        text="32-6487",
                                        rectSize=(243, 163)),
                        layer=3)
        all_sprites.add(LcarsElbow(colours.BLUE5, 0, (875, 116)), layer=3)
        all_sprites.add(LcarsImageBlock(colours.BLUE4,
                                        pos=(904, 398),
                                        rectSize=(1074, 43)),
                        layer=3)
        all_sprites.add(LcarsImageBlock(colours.BLUE3,
                                        pos=(875, 1478),
                                        rectSize=(44, 72)),
                        layer=3)
        all_sprites.add(LcarsElbow(colours.BLUE5, 3, (875, 1528)), layer=3)
        self.file_address = LcarsText(
            colours.BLACK, (900, 450),
            "NO MEDIA SELECTED",
            textSize=.75,
            fontFace="assets/OpenSansCondensed-Bold.ttf")
        all_sprites.add(self.file_address, layer=3)

        self.list_block = all_sprites.get_sprites_from_layer(3)

        #self.VIDEO_1_PATH = "./assets/video/LittleShopofHorrors1960Color.mp4"
        ### sound effects
        self.beep1 = Sound("assets/audio/panel/201.wav")
        self.lastClockUpdate = 0
        #Sound("assets/audio/panel/220.wav").play()

        ############ End base screen #############

    def dirlist(self, dirPath='./assets/video'):
        #os.scandir(dirPath)
        file_names = []
        for item in os.scandir(dirPath):
            if item.is_file() or item.is_dir():
                file_names.append(item.name)
        return file_names

    def update(self, screenSurface, fpsClock):
        if pygame.time.get_ticks() - self.lastClockUpdate > 500:
            if self.fileList.visible == True:
                if self.fileList.get_state() == None:
                    self.file_address.setText("NO MEDIA SELECTED")
                else:
                    self.file_address.setText(self.fileList.get_state())
            self.lastClockUpdate = pygame.time.get_ticks()
        LcarsScreen.update(self, screenSurface, fpsClock)

    def handleEvents(self, event, fpsClock):
        if event.type == pygame.MOUSEBUTTONDOWN:
            self.beep1.play()

        if event.type == pygame.MOUSEBUTTONUP:
            return False

    def playHandler(self, item, event, clock):
        try:
            self.player.play_pause()
        except:
            try:
                self.VIDEO_1_PATH = './assets/video/' + self.fileList.get_state(
                )
                self.player = OMXPlayer(
                    self.VIDEO_1_PATH,
                    dbus_name='org.mpris.MediaPlayer2.omxplayer1')
                self.player.set_aspect_mode('stretch')
                self.player.set_video_pos(116, 94, 1804, 947)
                self.player.set_alpha(255)
                self.showhide(self.list_block)
            except:
                pass

    def rewHandler(self, item, event, clock):
        try:
            self.player.action(omxkey.REWIND)
        except:
            pass

    def showhide(self, listofitems):
        for items in listofitems:
            items.visible = not items.visible

    def stopHandler(self, item, event, clock):

        try:
            self.player.stop()
            self.showhide(self.list_block)
        except:
            pass

    def ffHandler(self, item, event, clock):
        try:
            self.player.action(omxkey.FAST_FORWARD)
        except:
            pass

    ###### Screen Handling #####

    def mainHandler(self, item, event, clock):
        try:
            self.player.stop()
        except:
            pass
        from screens.base import ScreenBase
        self.loadScreen(ScreenBase())

    def logoutHandler(self, item, event, clock):
        from screens.authorize import ScreenAuthorize
        self.loadScreen(ScreenAuthorize())

    def libraryHandler(self, item, event, clock):
        from screens.library import ScreenLibrary
        self.loadScreen(ScreenLibrary())
Exemplo n.º 10
0
VIDEO_PATH_OPENING = Path("./assets/opening.mp4")
VIDEO_PATH_BATTLE = Path("./assets/battle-test.mp4")

player_opening = OMXPlayer(VIDEO_PATH_OPENING, args=['--no-osd'], pause=True)

#player_battle = OMXPlayer(VIDEO_PATH_BATTLE)
#player_battle.pause()

sleep(5)

player_opening.play()

sleep(3)

player_opening.stop()
player_opening.quit()
print("quit opening player")

#sleep(3)

#print("creating new player instance for the battle")

#player_battle = OMXPlayer(VIDEO_PATH_BATTLE)

#sleep(5)

#player_battle.stop()

#sleep(3)
Exemplo n.º 11
0
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()
Exemplo n.º 12
0
class Player:

    def __init__(self, video_file):
        self.player = None
        self.path = ''
        self.load(video_file)

    def load(self, video_file):
        print('Player loading {0}'.format(video_file))
        #if self.player != None:
        #    self.player.stop()
        #    del self.player
        self.path = os.path.join(media_dir, video_file)
        if self.player is None:
            self.player = OMXPlayer(self.path, args=['--loop', '--blank', '-o', 'both'])
        else:
            self.player.load(self.path)
        self.player.stopEvent += lambda _: self._complete()
        self.player.pauseEvent += lambda _: self._pauseEvent()
        self.player.playEvent += lambda _: self._playEvent()
        self.player.positionEvent += lambda _: self._positionEvent()
        self.player.seekEvent += lambda _: self._seekEvent()

    def _complete(self):
        print('Playback finished.')
   
    def _pauseEvent(self):
        print('Player pause event.')
   
    def _playEvent(self):
        print('Player play event.')

    def _positionEvent(self):
        print('Player position event.')

    def _positionEvent(self):
        print('Player seek event.')

    def set_pause(self, p):
        if p:
            self.player.pause()
        else:
            self.player.play()

    def get_pause(self):
        if self.player.is_playing():
            return False
        else:
            return True

    def toggle_pause(self):
        if self.player.is_playing():
            self.player.pause()
        else:
            self.player.play()

    def stop(self):
        self.player.stop()

    def quit(self):
        self.player.quit()

    def reload(self):
        print('Reloading {0}'.format(self.path))
        self.load(self.path)

    def get_path(self):
        return self.path
Exemplo n.º 13
0
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)
Exemplo n.º 14
0
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 = []
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
def main():
	userSelectedStream = 0
	GPIO.add_event_detect(ButtonPin, GPIO.RISING, bouncetime=500)	#set up button detechtion with debounce

	while True:	##main loop
		#check connection and fetch API
		while True:
			ApiData = fetch_Camera_API(droneRxIP,apiURL)		#Get Camera list
			if len(ApiData) > 0:
				CamCount = len(ApiData) 		#count number of camera objects in json file
				print("Camera Count: ",CamCount)	#count number of camears
				CamInfo={}
				CamInfo.clear()
				#fetch API Infomation
				for x in range(CamCount):		#get Cam Name, Stream and Drone Named
					CamInfo[x] = {}
					CamInfo[x]['Name'] = ApiData[x]['camera_name']
					CamInfo[x]['Stream'] = ApiData[x]['rtsp_link']
					CamInfo[x]['Flyer'] = ApiData[x]['flyer_name']
					print(CamInfo[x]['Name'], "-", CamInfo[x]['Stream'], "-", CamInfo[x]['Flyer'])
				break



		userSelectedStream = Stream_Selection_button(CamInfo,userSelectedStream)   ##check selected camera number is real


		#Start player and check for button selection
		while True:
			if GPIO.event_detected(ButtonPin):					#check button has been pressed
				print('Button pressed')
				userSelectedStream = userSelectedStream + 1			#increment selected stream by 1
				userSelectedStream = Stream_Selection_button(CamInfo,userSelectedStream)

			try:
				if player1.is_playing() == True:
					print("got here")
					if CamInfo[userSelectedStream]['Stream'] != player1.get_source():
						print("got here2")
						if do_CheckCamUrlStatus(CamInfo, userSelectedStream) == True:
							player1.load(CamInfo[userSelectedStream]['Stream'])
							lcd.clear()							#print message to LCD
							lcd.message("Streaming\n")
							lcd.message(CamInfo[userSelectedStream]['Name'])
						else:
							try:
								player1.stop()
							except:
								pass
							print("Stream does not exist123")
							lcd.clear()
							lcd.print("Stream does not\n")
							lcd.print("exist")
							sleep(1)
							break
					else:
						print("Currently Streaming",player1.get_source())
			except:
				if do_CheckCamUrlStatus(CamInfo, userSelectedStream) == True:
					print("expection got here")							####fix for chogm
					print(CamInfo[userSelectedStream]['Stream'])		####fix for chogm
					try:
						player1 = OMXPlayer(CamInfo[userSelectedStream]['Stream'], args=['-n','-1', '--live','-b', '--no-osd'])  #-n -1 turns of audio decode
						print("expection got here!!!!!2")							####fix for chogm
						lcd.clear()							#print message to LCD
						lcd.message("Streaming\n")
						lcd.message(CamInfo[userSelectedStream]['Name'])
					except:
						print("error here")
						try:
							player1.stop()
						except:
							pass
						print("Stream does not exist")
						lcd.clear()
						lcd.message("Stream does not\n")
						lcd.message("exist")
						sleep(1)
						break
				


				else:
					try:
						player1.stop()
					except:
						pass
					print("Stream does not exist")
					lcd.clear()
					lcd.message("Stream does not\n")
					lcd.message("exist")
					sleep(1)
					break

			sleep(.1)
Exemplo n.º 17
0
class ScreenController:
    video_playlist = []
    player1 = None
    player2 = None
    index = None
    index = None

    def __init__(self):
        self.video_playlist = [
            VideoFile(1, "/media/pi/TOSHIBA1/Apocalyptic.mp4"),
            VideoFile(2, "/media/pi/TOSHIBA1/ledtime.mp4")
        ]
        self.index = 0
        self.player_log = logging.getLogger("Player")

    def setup_player_one(self):
        self.player1 = OMXPlayer(self.video_playlist[self.index].path,
                                 args='--win 0,0,1920,1080 --layer 2',
                                 bus_address_finder=None,
                                 Connection=None,
                                 dbus_name='orb.mpris.MediaPlayer2.omxplayer1',
                                 pause=True)
        self.player1.playEvent += lambda _: self.player_log.info(" 1 Play")
        self.player1.pauseEvent += lambda _: self.player_log.info("1 Pause")
        self.player1.stopEvent += lambda _: self.player_log.info("1 Stop")

    def setup_player_two(self):
        self.player2 = OMXPlayer(self.video_playlist[self.index + 1].path,
                                 args='--win 0,0,1920,1080 --layer 3',
                                 bus_address_finder=None,
                                 Connection=None,
                                 dbus_name='orb.mpris.MediaPlayer2.omxplayer2',
                                 pause=True)
        self.player2.playEvent += lambda _: self.player_log.info(" 2 Play")
        self.player2.pauseEvent += lambda _: self.player_log.info("2 Pause")
        self.player2.stopEvent += lambda _: self.player_log.info("2 Stop")

    def start_playlist(self):
        self.setup_player_one()
        self.setup_player_two()
        self.play_videos()

    def play_videos(self):
        alpha1 = 255
        self.player1.load(self.video_playlist[self.index].path, True)
        self.player2.load(self.video_playlist[self.index + 1].path, True)

        self.player1.play()
        while self.is_nearly_finished(self.player1) == False:
            sleep(1)

        #while self.is_nearly_finished(self.player1) == True and alpha1 > 0:
        #reductionRate = self.get_remaining_seconds(self.player1)
        #alpha1 = alpha1 - reductionRate
        #self.player1.set_alpha(alpha1)
        #sleep(1)

        self.player2.play()
        self.player1.stop()

        while self.is_nearly_finished(self.player2) == False:
            sleep(1)
        self.player2.stop()

    def get_remaining_seconds(self, player):
        remaining_seconds = player.duration() - player.position()
        return remaining_seconds

    def is_nearly_finished(self, player):
        amountPlayed = 0
        if player.position() > 0:
            amountPlayed = player.position()
        percentPlayed = amountPlayed / player.duration()
        print(percentPlayed)
        if (percentPlayed > 0.9):
            return True
        else:
            return False
Exemplo n.º 18
0
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,
        }
Exemplo n.º 19
0
player_stop = OMXPlayer(BLACK_PATH, 
        dbus_name='org.mpris.MediaPlayer2.omxplayer2')

# it takes about this long for omxplayer to warm up and start displaying a picture on a rpi3
player_action.pause()
sleep(2.5)
player_stop.pause()
try:
    while True:
         # Button was pressed
         
        if ( GPIO.input(button) == GPIO.LOW ):
            sleep(1)
            try:
                if (player_action.is_playing() == True):
                    player_action.stop()
                    sleep(1)
                    player_action = OMXPlayer(VIDEO_PATH, dbus_name='org.mpris.MediaPlayer2.omxplayer1')
                else:
                    player_action.play()
                    sleep(1)
            except:
                sleep(1)
                    
                
                
            
except KeyboardInterrupt:
    try:
        player_action.quit()
        player_stop.quit()
Exemplo n.º 20
0
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
Exemplo n.º 21
0
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()