Пример #1
0
def play_radio(event):
    print("Play radio")

    global player
    global mode
    global currentStation

    if player is not None:
        print("Already playing - quit")
        player.quit()
        player = None
        mode = None
    else:
        print("Start online radio player")

        for key, value in radioStations.items():
            player = OMXPlayer(value)

            print(key)
            currentStation = key

            break

        player.pause()

        mode = "radio"
        player.play()
        print("Play")
Пример #2
0
 def thread_target(self):
     while True:
         self.recData=com.Receive()
         #ここに受け取ったデータ: recDataをphantomからrealに変換し、
         #real側でくっつけて、返すものが求められる
         if (self.recData != 0 and self.recData is not None):
             #<Playing>
             print "start play"
             player = OMXPlayer("movs/"+dictRM[dictPR[str(self.recData)]]+".mp4")
             player.play()
             time.sleep(14)
             player.pause()
             #if you got to quit you can't re-open
             player.quit()
             global realData
             realData="After"
             print "[After?]: ",realData,"[.]"
             #global MainFrame
             #MainFrame.Close()
             #MainApp = wx.App()
             #MainFrame = CFrame()
             #MainFrame.Center()
             #MainFrame.Show()
             #MainApp.MainLoop()
         #<loopTest
         self.forTesCount+=1
         if self.forTesCount%1000 == 0:
             print "recNOW"
         #loopTest>
         time.sleep(0.01)
def play_some_commercials(max_commercials_per_break):
	try:
		comm_source = get_random_commercial()
		comm_player = OMXPlayer(comm_source, args=['--no-osd', '--blank'], dbus_name="omxplayer.player1")
		comm_player.set_video_pos(40,10,660,470);
		comm_player.set_aspect_mode('fill');
		comm_player.hide_video()
		comm_player.pause()
		#comm_player.set_volume(-1)
		comm_i = max_commercials_per_break
		while(comm_i>=0):
			comm_source = get_random_commercial()
			print('Playing commercial #' + str(comm_i), comm_source)
			contents = urllib2.urlopen("http://127.0.0.1/?current_comm=" + urllib.quote_plus(comm_source)).read()
			comm_player.load(comm_source)
			comm_player.pause()
			sleep(0.1)
			if comm_i==4:
				comm_player.show_video()
				
			comm_player.play()
			err_pos = 4
			while (1):
				try:
					comm_position = math.floor(comm_player.position())
				except:
					break
			comm_i = comm_i - 1
			sleep(1)
	except:
		print("Error playing commercial from function")
Пример #4
0
def StartClick(event):#forSTARTbutton:!!!!need be changed!!!!!!!!!!!!!
    STATbutton.SetBackgroundColour("#0000FF")#JustForTest
    #<Playing>
    player = OMXPlayer("movs/"+dictRM[realData]+".mp4")
    player.play()
    time.sleep(3)
    player.pause()
    #if you got to quit you can't re-open
    player.quit()
Пример #5
0
def music():
    text = "wow, exciting song"
    file_path='/home/pi/music.mp3'
    player=OMXPlayer(file_path)
    player.play()
    sleep(7)
    player.pause()
    player.quit()
    return statement(text)
Пример #6
0
def playAlert():
    global done
    global playOnce

    done = False
    playOnce = False

    if playOnce == False:
        #pygame.init()
        #pygame.display.set_mode([100,100])
        done = False
        #print "initialize pygame window"
        omxp = OMXPlayer(sound_path)
        omxp.play()
        print 'Playing Sound'
        omxp.pause()
        playOnce = True

    while True:

        #        for event in pygame.event.get():
        #            print "for loop getting event"
        #            if event.type == pygame.QUIT:
        #                done = True
        #                print "pygame.QUIT event"
        #            elif event.type == pygame.KEYDOWN:
        #                if event.key == pygame.K_ESCAPE:
        #                    done = True
        #                    playOnce = False
        #                    omxp.quit()
        #pygame.display.quit()
        #                    print "escape key pressed"
        #                elif event.key == pygame.K_F1:
        #                    if (omxp.playback_status() == "Playing"):
        #                        print(omxp.playback_status())
        #                    elif (omxp.playback_status() == "Paused"):
        #                        print(omxp.playback_status())
        #                    elif (omxp.playback_status() == "Stopped"):
        #                        print(omxp.playback_status())
        #                    else:
        #                        print "Unknown player status, quit player"
        #                        playOnce = False
        #                        omxp.quit()
        #pygame.display.quit()

        if (omxp.playback_status() == "Stopped"):
            print "alert ended"
            playOnce = False
            #done = True
            omxp.quit()
            break
Пример #7
0
def omxplayer_process(queue):
    try:
        player_num = 0
        last_video = None
        video = True
        while video:
            #log.debug("Warte auf Befehle")
            video = queue.get()
            try:
                # block queue
                queue.put_nowait(True)
            except:
                ...
            log.debug('Play {}'.format(video))
            if not last_video == video:
                try:
                    player.quit()
                except:
                    killall_omxplayer()
                log.debug('Load new Video: {}'.format(video))
                dbus_name = 'org.mpris.MediaPlayer2.omxplayer{}'.format(
                    player_num)
                player = OMXPlayer(video,
                                   args=omxplayer_args,
                                   dbus_name=dbus_name,
                                   pause=True)
                player_num += 1
                #log.debug(player.volume())
                player.set_volume(1.0)
                time.sleep(1)

            # das erste Video soll nicht abgespielt werden, sondern nur einen Kaltstart vermeiden
            if not last_video == None:
                player.set_alpha(255)
                player.play_sync()
                player.pause()
                player.set_alpha(0)
                player.set_position(0)
                log.debug('Video fertig: {}'.format(video))

            last_video = video

            try:
                # clean queue
                queue.get_nowait()
            except:
                ...
    except KeyboardInterrupt:
        ...
    finally:
        killall_omxplayer()
Пример #8
0
def testVideo(video_id=None):
    print "Incoming video request"
    vid1 = OMXPlayer(TEST_MEDIA_FILE_1, pause=True)
    print("Start playing")
    vid1.set_position(70)
    dur = vid1.duration()
    print dur
    vid1.play()
    sleep(2)
    print("Stop playing")
    vid1.pause()
    time.sleep(2)
    vid1.load(TEST_MEDIA_FILE_2)
    vid1.play()
    sleep(2)
    print("Exit")
    vid1.quit()
Пример #9
0
def reset_handler():
    emit("reset", "", broadcast=True)
    global firstTrigger
    firstTrigger = True
    global occupied
    occupied = False
    global player
    player = OMXPlayer(VIDEO_FILE_3, args=['--no-osd', '--no-keys', '-b'])
    player.play()
    sleep(1)
    player.pause()
    ledDriver.setPWM(UPPER_SHELL_RED, 4095, 0)
    ledDriver.setPWM(UPPER_SHELL_GREEN, 4095, 0)
    ledDriver.setPWM(UPPER_SHELL_BLUE, 4095, 0)
    ledDriver.setPWM(UNDER_SEAT_PWM_R, 4095, 0)
    ledDriver.setPWM(UNDER_SEAT_PWM_G, 4095, 0)
    ledDriver.setPWM(UNDER_SEAT_PWM_B, 4095, 0)
Пример #10
0
def testVideo(video_id=None):
    print "Incoming video request"
    vid1 = OMXPlayer(TEST_MEDIA_FILE_1, pause=True)
    print("Start playing")
    vid1.set_position(70)
    dur = vid1.duration()
    print dur
    vid1.play()
    sleep(2)
    print("Stop playing")
    vid1.pause()
    time.sleep(2)
    vid1.load(TEST_MEDIA_FILE_2)
    vid1.play()
    sleep(2)
    print("Exit")
    vid1.quit()
Пример #11
0
class PlayVoidAudio(Thread):
    def __init__(self):
        Thread.__init__(self)

    def terminate(self):  # activated by Stop button
        self.player.stop()
        print('Terminating thread...')

    def run(self):

        self.player = OMXPlayer(
            '/home/pi/donics/MoS_TimingRemix_3Void_CleanStartEnd.mp3')
        self.player.pause()
        self.player.pause()
        self.player.set_position(0.0)
        #time.sleep(.1)
        print "play"
        self.player.play()
Пример #12
0
def play_mp3(event):
    print("Play mp3")

    global player
    global mode

    if player is not None:
        print("Already playing - quit")
        player.quit()
        player = None
        mode = None
    else:
        print("Start player")
        player = OMXPlayer('/home/pi/mp3/Beck.mp3')
        player.pause()
        mode = "MP3"
        player.play()
        print("Play")
Пример #13
0
class TV(threading.Thread):
    def __init__(self):
        super(TV, self).__init__()
        print("Initializing TV")
        self.red_alert = False
        self.player = None
        self.reset()

        #Register Events
        signal('SYSTEM_stopping').connect(self.clean_up)
        signal('tv.redalert').connect(self.alert)
        signal('alert.red.toggle').connect(self.alert)
        signal('code_47').connect(self.reset)

    def reset(self, sender='anonymous'):
        os.system('pkill omxplayer')
        self.player = OMXPlayer("http://repo.posttwo.pt/redalert.mp4",
                                args=['--no-osd', '--no-keys', '-b', '--loop'])
        self.player.pause()

    def tv_set_pi(self):
        subprocess.call("echo 'as' | cec-client -s &", shell=True)
        #os.system('echo "as" | cec-client -s')

    def tv_set_chrome(self):
        subprocess.call("echo 'txn 4f:82:20:00' | cec-client -s &", shell=True)
        #os.system('echo "txn 4f:82:20:00" | cec-client -s')

    def alert(self, sender='anonymous'):
        if not self.red_alert:
            self.red_alert = True
            self.tv_set_pi()
            print("RED ALERT ON")
            self.player.set_position(0)
            self.player.play()
        else:
            self.red_alert = False
            self.tv_set_chrome()
            self.player.pause()

    def clean_up(self, sender='anonymous'):
        print("TV Cleaning Up")
        self.player.quit()
Пример #14
0
def start_up():

    GPIO.setup(PROJECTOR_MENU, GPIO.OUT)
    GPIO.setup(PROJECTOR_ON_OFF, GPIO.OUT)
    GPIO.setup(AUDIO_LED, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(AUDIO_PLUG_DETECT, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(SEAT_OCCUPANCY, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    #GPIO.add_event_detect(SEAT_OCCUPANCY, GPIO.FALLING, callback = seat_occupied, bouncetime = 200)
    #GPIO.add_event_detect(AUDIO_PLUG_DETECT, GPIO.FALLING, callback = audio_plug_insert, bouncetime = 200)
    GPIO.output(PROJECTOR_MENU, GPIO.LOW)
    GPIO.output(PROJECTOR_ON_OFF, GPIO.HIGH)
    sleep(1.0)
    GPIO.output(PROJECTOR_ON_OFF, GPIO.LOW)
    sleep(25.0)
    # pulse 3 times to select HDMIi
    print "pulse for hdmi"
    GPIO.output(PROJECTOR_MENU, GPIO.HIGH)
    sleep(0.7)
    GPIO.output(PROJECTOR_MENU, GPIO.LOW)
    sleep(0.7)
    GPIO.output(PROJECTOR_MENU, GPIO.HIGH)
    sleep(0.7)
    GPIO.output(PROJECTOR_MENU, GPIO.LOW)
    sleep(0.7)
    GPIO.output(PROJECTOR_MENU, GPIO.HIGH)
    sleep(0.7)
    GPIO.output(PROJECTOR_MENU, GPIO.LOW)
    sleep(3)

    player = OMXPlayer(VIDEO_FILE_1)
    player.play()
    # now what ?
    print "started"
    sleep(5)

    player.pause()
    sleep(3.0)
    player.quit()
    player = OMXPlayer(VIDEO_FILE_2)
    player.play()
    sleep(2)
    player.quit()
Пример #15
0
 def thread_target(self):
     while True:
         self.recData = com.Receive()
         #ここに受け取ったデータ: recDataをphantomからrealに変換し、
         #real側でくっつけて、返すものが求められる
         if (self.recData != 0 and self.recData is not None):
             #<Playing>
             print "start play"
             player = OMXPlayer("movs/" +
                                dictRM[dictPR[str(self.recData)]] + ".mp4")
             player.play()
             time.sleep(3)
             player.pause()
             #if you got to quit you can't re-open
             player.quit()
         #<loopTest
         self.forTesCount += 1
         if self.forTesCount % 1000 == 0:
             print "recNOW"
         #loopTest>
         time.sleep(0.01)
Пример #16
0
class Player:
    def __init__(self, path):
        self.path = path
        self.player = OMXPlayer(
            self.path, args=["--loop", "-o", "local", "--win", "0,0,640,480"])
        # self.player.play()
        # self.player.set_position(10.0)
        # self.player.pause()

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

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

    def toggle(self):
        self.player.play_pause()

    def reset(self):
        self.player.pause()
        self.player.set_position(0.0)
Пример #17
0
def basic_func():
    try:
        print(commands)
        print(commands["play_pause"])
        directory = create_playlist()
        shuffle(directory)
        print("currently, my playlist is {}".format(directory))
        my_playlist_length = len(directory)
        my_song_index = 0
        my_song = directory[0]
        print("My song right now is {}".format(my_song))
        player = OMXPlayer(my_song)
        print("player initialized")
        player.pause()
        my_volume = player.volume()
        while True:
            if player.position() >= player.duration() - 1.5:
                sleep(0.2)
                commands["skip"] = True
            if commands["play_pause"]:
                if not player.is_playing():
                    sleep(0.2)
                    print("I was paused, now I'm playing")
                    player.play()
                elif player.is_playing():
                    sleep(0.2)
                    player.pause()
                print(player.duration())
                print(player.position())
                commands["play_pause"] = False
            if commands["stop"]:
                sleep(0.2)
                player.stop()
                commands["stop"] = False
            if commands["quieter"]:
                sleep(0.2)
                my_volume = player.volume()
                my_volume = my_volume - 100
                player.set_volume(my_volume)
                print(my_volume)
                commands["quieter"] = False
            if commands["louder"]:
                sleep(0.2)
                my_volume = player.volume()
                if my_volume <= 900:
                    my_volume = my_volume + 100
                player.set_volume(my_volume)
                print(my_volume)
                commands["louder"] = False
            if commands["quit"]:
                sleep(0.2)
                print("run")
                player.quit()
                print("run 2")
                subprocess.check_call(["python", "/home/pi/startup.py"])
                print("run 3")
                break
            if commands["skip"]:
                sleep(0.2)
                player.quit()
                my_song_index = (my_song_index + 1) % my_playlist_length
                if my_song_index == 0:
                    print("my playlist was {}".format(directory))
                    shuffle(directory)
                    print("my playlist is now {}".format(directory))

                my_song = directory[my_song_index]
                player = OMXPlayer(my_song)
                player.set_volume(my_volume)
                commands["skip"] = False

                print("Now, my_song is {}".format(my_song))

    except:
        GPIO.cleanup()
        player.quit()
import sys
from omxplayer import OMXPlayer
from time import sleep


args = ['-vol -1500.00']
#player = OMXPlayer(sys.argv[1], args=['--no-osd', '--no-keys', '-b'])
player = OMXPlayer(sys.argv[1], args=args)
#player = OMXPlayer(sys.argv[1])


#player.set_volume(-1500.00)
player.play()
sleep(5)
player.pause()

player.quit()
Пример #19
0
class MediaOmxplayerPlugin(MediaPlugin):
    """
    Plugin to control video and media playback using OMXPlayer.

    Requires:

        * **omxplayer** installed on your system (see your distro instructions)
        * **omxplayer-wrapper** (``pip install omxplayer-wrapper``)
    """

    def __init__(self, args=None, *argv, **kwargs):
        """
        :param args: Arguments that will be passed to the OMXPlayer constructor
            (e.g. subtitles, volume, start position, window size etc.) see
            https://github.com/popcornmix/omxplayer#synopsis and
            http://python-omxplayer-wrapper.readthedocs.io/en/latest/omxplayer/#omxplayer.player.OMXPlayer
        :type args: list
        """

        super().__init__(*argv, **kwargs)

        if args is None:
            args = []

        self.args = args
        self._player = None
        self._handlers = {e.value: [] for e in PlayerEvent}

    @action
    def play(self, resource, subtitles=None, *args, **kwargs):
        """
        Play a resource.

        :param resource: Resource to play. Supported types:

            * Local files (format: ``file://<path>/<file>``)
            * Remote videos (format: ``https://<url>/<resource>``)
            * YouTube videos (format: ``https://www.youtube.com/watch?v=<id>``)
            * Torrents (format: Magnet links, Torrent URLs or local Torrent files)

        :param subtitles: Subtitles file
        """

        if subtitles:
            args += ('--subtitles', subtitles)

        resource = self._get_resource(resource)
        if self._player:
            try:
                self._player.stop()
                self._player = None
            except Exception as e:
                self.logger.exception(e)
                self.logger.warning('Unable to stop a previously running instance ' +
                                    'of OMXPlayer, trying to play anyway')

        from dbus import DBusException

        try:
            from omxplayer import OMXPlayer
            self._player = OMXPlayer(resource, args=self.args)
            self._init_player_handlers()
        except DBusException as e:
            self.logger.warning('DBus connection failed: you will probably not ' +
                                'be able to control the media')
            self.logger.exception(e)

        self._player.pause()
        if self.volume:
            self.set_volume(volume=self.volume)

        self._player.play()
        return self.status()

    @action
    def pause(self):
        """ Pause the playback """
        if self._player:
            self._player.play_pause()
        return self.status()

    @action
    def stop(self):
        """ Stop the playback (same as quit) """
        return self.quit()

    @action
    def quit(self):
        """ Quit the player """
        from omxplayer.player import OMXPlayerDeadError

        if self._player:
            try:
                self._player.stop()
                self._player.quit()
            except OMXPlayerDeadError:
                pass

            self._player = None

        return {'status': 'stop'}

    @action
    def voldown(self):
        """ Volume down by 10% """
        if self._player:
            self._player.set_volume(max(0, self._player.volume()-0.1))
        return self.status()

    @action
    def volup(self):
        """ Volume up by 10% """
        if self._player:
            self._player.set_volume(min(1, self._player.volume()+0.1))
        return self.status()

    @action
    def back(self, offset=60):
        """ Back by (default: 60) seconds """
        if self._player:
            self._player.seek(-offset)
        return self.status()

    @action
    def forward(self, offset=60):
        """ Forward by (default: 60) seconds """
        if self._player:
            self._player.seek(offset)
        return self.status()

    @action
    def next(self):
        """ Play the next track/video """
        if self._player:
            self._player.stop()

        if self._videos_queue:
            video = self._videos_queue.pop(0)
            self.play(video)

        return self.status()

    @action
    def hide_subtitles(self):
        """ Hide the subtitles """
        if self._player:
            self._player.hide_subtitles()
        return self.status()

    @action
    def hide_video(self):
        """ Hide the video """
        if self._player:
            self._player.hide_video()
        return self.status()

    @action
    def is_playing(self):
        """
        :returns: True if it's playing, False otherwise
        """

        return self._player.is_playing()

    @action
    def load(self, resource, pause=False, **kwargs):
        """
        Load a resource/video in the player.

        :param resource: URL or filename to load
        :type resource: str

        :param pause: If set, load the video in paused mode (default: False)
        :type pause: bool
        """

        if self._player:
            self._player.load(resource, pause=pause)
        return self.status()

    @action
    def metadata(self):
        """ Get the metadata of the current video """
        if self._player:
            return self._player.metadata()
        return self.status()

    @action
    def mute(self):
        """ Mute the player """
        if self._player:
            self._player.mute()
        return self.status()

    @action
    def unmute(self):
        """ Unmute the player """
        if self._player:
            self._player.unmute()
        return self.status()

    @action
    def seek(self, relative_position):
        """
        Seek backward/forward by the specified number of seconds

        :param relative_position: Number of seconds relative to the current cursor
        :type relative_position: int
        """

        if self._player:
            self._player.seek(relative_position)
        return self.status()

    @action
    def set_position(self, position):
        """
        Seek backward/forward to the specified absolute position

        :param position: Number of seconds from the start
        :type position: int
        """

        if self._player:
            self._player.seek(position)
        return self.status()

    @action
    def set_volume(self, volume):
        """
        Set the volume

        :param volume: Volume value between 0 and 100
        :type volume: int
        """

        if self._player:
            self._player.set_volume(volume/100)
        return self.status()

    @action
    def status(self):
        """
        Get the current player state.

        :returns: A dictionary containing the current state.

        Format::

            output = {
                "duration": Duration in seconds,
                "filename": Media filename,
                "fullscreen": true or false,
                "mute": true or false,
                "path": Media path
                "pause": true or false,
                "position": Position in seconds
                "seekable": true or false
                "state": play, pause or stop
                "title": Media title
                "url": Media url
                "volume": Volume between 0 and 100
                "volume_max": 100,
            }
        """

        from omxplayer.player import OMXPlayerDeadError

        if not self._player:
            return {
                'state': PlayerState.STOP.value
            }

        try:
            state = self._player.playback_status().lower()
        except OMXPlayerDeadError:
            self._player = None
            return {
                'state': PlayerState.STOP.value
            }

        if state == 'playing':
            state = PlayerState.PLAY.value
        elif state == 'stopped':
            state = PlayerState.STOP.value
        elif state == 'paused':
            state = PlayerState.PAUSE.value

        return {
            'duration': self._player.duration(),
            'filename': urllib.parse.unquote(self._player.get_source()).split('/')[-1] if self._player.get_source().startswith('file://') else None,
            'fullscreen': self._player.fullscreen(),
            'mute': self._player._is_muted,
            'path': self._player.get_source(),
            'pause': state == PlayerState.PAUSE.value,
            'position': max(0, self._player.position()),
            'seekable': self._player.can_seek(),
            'state': state,
            'title': urllib.parse.unquote(self._player.get_source()).split('/')[-1] if self._player.get_source().startswith('file://') else None,
            'url': self._player.get_source(),
            'volume': self._player.volume() * 100,
            'volume_max': 100,
        }

    def add_handler(self, event_type, callback):
        if event_type not in self._handlers.keys():
            raise AttributeError('{} is not a valid PlayerEvent type'.
                                 format(event_type))

        self._handlers[event_type].append(callback)

    @staticmethod
    def _post_event(evt_type, **evt):
        bus = get_bus()
        bus.post(evt_type(player='local', plugin='media.omxplayer', **evt))

    def on_play(self):
        def _f(player):
            resource = player.get_source()
            self._post_event(MediaPlayEvent, resource=resource)
            for callback in self._handlers[PlayerEvent.PLAY.value]:
                callback(resource)

        return _f

    def on_pause(self):
        def _f(player):
            resource = player.get_source()
            self._post_event(MediaPauseEvent, resource=resource)
            for callback in self._handlers[PlayerEvent.PAUSE.value]:
                callback(resource)

        return _f

    def on_stop(self):
        def _f(player):
            self._post_event(MediaStopEvent)
            for callback in self._handlers[PlayerEvent.STOP.value]:
                callback()
        return _f

    def on_seek(self):
        def _f(player):
            self._post_event(MediaSeekEvent, position=player.position())
        return _f

    def _init_player_handlers(self):
        if not self._player:
            return

        self._player.playEvent += self.on_play()
        self._player.pauseEvent += self.on_pause()
        self._player.stopEvent += self.on_stop()
        self._player.positionEvent += self.on_seek()
def play_video(source, commercials, max_commercials_per_break):
	if source==None:
		return
	#os.system("killall -9 omxplayer");
	try:
		global next_video_to_play
		global last_video_played
		
		err_pos = -1.0
		
		if next_video_to_play=='':
			print("Last video played: " + last_video_played)
			urlcontents = urllib2.urlopen("http://127.0.0.1/?getshowname=" + urllib.quote_plus(source)).read()
			print("Response: ")
			print(urlcontents)
			acontents = urlcontents.split("|")
			#if last_video_played == contents and contents!="News":
			if acontents[1]!="0" and acontents[0]!="News":
				print("Just played this show, skipping")
				return
			last_video_played = acontents[0]
			print("Last video played: " + last_video_played)
		
		next_video_to_play=''
		
		err_pos = 0.0

		comm_source = get_random_commercial()
		err_pos = 0.1
		comm_player = OMXPlayer(comm_source, args=['--no-osd', '--blank'], dbus_name="omxplayer.player1")
		err_pos = 0.12
		comm_player.set_video_pos(40,10,660,470);
		comm_player.set_aspect_mode('fill');
		err_pos = 0.13
		comm_player.hide_video()
		err_pos = 0.14
		comm_player.pause()
		err_pos = 0.15
		#comm_player.set_volume(1)
		err_pos = 0.2
		
		print('Main video file:' + source)
		err_pos = 0.21
		contents = urllib2.urlopen("http://127.0.0.1/?current_video=" + urllib.quote_plus(source)).read()
		err_pos = 0.23
		player = OMXPlayer(source, args=['--no-osd', '--blank'], dbus_name="omxplayer.player0")
		err_pos = 0.3
		print('Boosting Volume by ' + str(get_volume(source)) + 'db')
		err_pos = 0.31
		player.set_video_pos(40,10,660,470);
		player.set_aspect_mode('fill');
		err_pos = 0.32
		#player.set_volume(get_volume(source))
		err_pos = 0.33
		sleep(1)
		err_pos = 1.0
		player.pause()
		err_pos = 1.1
		strSubtitles = player.list_subtitles()
		if(strSubtitles):
			player.hide_subtitles()
		err_pos = 1.2
		player.play()
		err_pos = 1.3
		lt = 0
		while (1):
			err_pos = 2.0
			try:
				position = player.position()
			except:
				break

			if check_video()==True:
				#check if an outside source wants to play a new video
				print('outside source video return')
				err_pos = 8.0
				player.hide_video()
				player.quit()
				comm_player.hide_video()
				comm_player.quit()
				sleep(0.5)
				return
			
			if len(commercials) > 0:
				#found a commercial break, play some commercials
				if math.floor(position)==commercials[0]:
					commercials.pop(0)
					player.hide_video()
					player.pause()
					sleep(0.5)
					comm_i = max_commercials_per_break
					err_pos = 3.0
					while(comm_i>=0):
						if check_video()==True or next_video_to_play!='':
							#check if an outside source wants to play a new video
							print('outside source video return')
							err_pos = 6.0
							player.hide_video()
							player.quit()
							comm_player.hide_video()
							comm_player.quit()
							sleep(0.5)
							return
					
						comm_source = get_random_commercial()
						print('Playing commercial #' + str(comm_i), comm_source)
						contents = urllib2.urlopen("http://127.0.0.1/?current_comm=" + urllib.quote_plus(comm_source)).read()
						comm_player.load(comm_source)
						comm_player.pause()
						sleep(0.1)
						if comm_i==4:
							comm_player.show_video()
							
						comm_player.play()
						err_pos = 4.0
						while (1):
							try:
								comm_position = math.floor(comm_player.position())
							except:
								break
						comm_i = comm_i - 1
						sleep(1)
					
					err_pos = 5.0
					player.show_video()
					player.play()

		err_pos = 7.0
		player.hide_video()
		sleep(0.5)
	except Exception as e:
		if(err_pos!=7.0):
			contents = urllib2.urlopen("http://127.0.0.1/?error=MAIN_" + str(err_pos) + "_" + urllib.quote_plus(str(e))).read()
		print("error main " + str(e))

	try:
		comm_player.quit()
	except Exception as ex:
		#contents = urllib2.urlopen("http://127.0.0.1/?error=COMMERCIAL_" + str(err_pos) + "_" + urllib.quote_plus(str(ex))).read()
		print("error comm quit " + str(ex))
	try:
		player.quit()
	except Exception as exx:
		#contents = urllib2.urlopen("http://127.0.0.1/?error=PLAYER_" + str(err_pos) + "_" + urllib.quote_plus(str(exx))).read()
		print("error player quit " + str(exx))
	
	return
Пример #21
0
from omxplayer import OMXPlayer

a = 2

print("running initial setup")
loop1 = OMXPlayer('FILE PATH',
                  args=['--win', '100 100 640 480',
                        '--loop'])  #ARGS FOR THE CONTROL OF THE WINDOW SIZE
vid1 = OMXPlayer('FILE PATH', args=['--win', '100 100 480 360'])

while a == 2:
    print("Motion detection activated")
    time.sleep(2)
    print("Security system functioning")
    loop1.play()
    a = input()
    while a == 1:
        time.sleep(0.1)
        a = input()
        if a == 1:
            loop1.pause()
            print("Intruder Detected")
            vid1.play()
            print("Playing Vid_Name_Hammerstein")

        else:
            loop1.play()
            print("Intruder Detected")
            vid1.pause()
            print("Playing Vid_Name_Hammerstein")
Пример #22
0
class KuBo():
    def __init__(self,
                 servoPin=19,
                 lowerReedPin=17,
                 higherReedPin=22,
                 start_pos=900,
                 plate_dist=0.02,
                 plate_weight=5):
        self.servoPin = servoPin
        self.lowerReedPin = lowerReedPin
        self.higherReedPin = higherReedPin

        self.start_pos = start_pos  #The servo position at boot up

        self.plate_dist = plate_dist
        self.plate_weight = plate_weight

        self.pi = pigpio.pi()

        # Configure Pin Mode
        self.pi.set_mode(self.servoPin, pigpio.OUTPUT)
        self.pi.set_mode(self.lowerReedPin, pigpio.INPUT)
        self.pi.set_mode(self.higherReedPin, pigpio.INPUT)

        # Set position of servo to start position
        self.pi.set_servo_pulsewidth(self.servoPin, self.start_pos)

        # Parameters for the thread need to be lists to change their values
        # during thread execution
        self.end_pos_list = [0]
        self.freq_list = [0]

        # Start Audio Player process
        self.audiopath = '/home/pi/Documents/GitKubo/kubo/sounds/'
        self.omx = OMXPlayer(self.audiopath + 'ku.mp3')
        self.omx.pause()

        # Initiallize edge listener
        self.cb_lower = self.pi.callback(self.lowerReedPin, pigpio.RISING_EDGE,
                                         self._callback_lower)
        self.cb_higher = self.pi.callback(self.higherReedPin,
                                          pigpio.RISING_EDGE,
                                          self._callback_higher)

        # zero count parameters
        self.max_zero_count = 10
        #self.max_zero_count = 1000

        self.min_zero_count = 5

        # one count parameters
        self.min_one_count = 3

        # polling period
        self.T_poll = 0.001

        # lower reed contact data
        self.lower_speed = 0
        self.lower_weight = 0
        self.lower_flag = 0
        self.lower_timestamp = 0

        # higher reed contact data
        self.higher_speed = 0
        self.higher_weight = 0
        self.higher_flag = 0
        self.higher_timestamp = 0

        # Locks
        self.lock_lower = threading.Lock()
        self.lock_higher = threading.Lock()

        self.data = []

    def start_jumping(self, end_pos, freq):

        # check if thread is allready running
        if hasattr(self, 't_jump'):
            if self.t_jump.isAlive():
                print "Kubo is allready jumping... Let him take a break :D"
                return

        self.end_pos_list[0] = end_pos
        self.freq_list[0] = freq

        # Set Servo to starting value
        self.pi.set_servo_pulsewidth(self.servoPin, self.start_pos)

        # Create lock for thread values
        self.jump_lock = threading.Lock()

        # Create event that is triggered when thread should be stopped
        self.jump_stop = threading.Event()

        # Define thread
        self.t_jump = threading.Thread(target=self._jump_thread,
                                       args=(self.end_pos_list, self.freq_list,
                                             self.jump_stop))

        self.t_jump.start()

    def _jump_thread(self, end_pos_list, freq_list, stop_event):
        print "Thread started"
        while (not stop_event.is_set()):
            with self.jump_lock:
                print "End position: ", end_pos_list[0]
                print "Frequency: ", freq_list[0]

                # Calculate the settle time the servo needs for moving
                # Convert pulsewidth to degrees
                degree = (end_pos_list[0] - self.start_pos) / 10
                # Servo speed is 0.15s/60deg
                # Safety factor of 1.1
                settle = 0.15 / 60 * degree * 1.1

                self.pi.set_servo_pulsewidth(self.servoPin, end_pos_list[0])
                time.sleep(settle)
                self.pi.set_servo_pulsewidth(self.servoPin, self.start_pos)
                time.sleep(settle)
                if freq_list[0] != 0:
                    sleep_time = 1 / freq_list[0] - 2 * settle
                else:
                    break

            if sleep_time > 0:
                time.sleep(sleep_time)
            elif sleep_time < 0:
                print "Frequency too high"
        print "Thread stopped"

    def stop_jumping(self):
        if not hasattr(self, 't_jump'):
            print "Kubo needs to start jumping first"
            return
        else:
            if not self.t_jump.isAlive():
                print "Kubo needs to start jumping first"
                return

        self.jump_stop.set()

    def change_jumping(self, end_pos, freq):
        if not hasattr(self, 't_jump'):
            print "Kubo needs to start jumping first"
            return
        else:
            if not self.t_jump.isAlive():
                print "Kubo needs to start jumping first"
                return

        with self.jump_lock:
            self.end_pos_list[0] = end_pos
            self.freq_list[0] = freq

    def is_jumping(self):
        if not hasattr(self, 't_jump'):
            return False
        else:
            return self.t_jump.isAlive()

    def say(self, filename):
        #self.omx.quit()
        return self.omx.load(self.audiopath + filename)

    def init_voice(self, audiopath='/home/pi/Documents/Audio/'):
        self.audiopath = audiopath
        self.omx = OMXPlayer(self.audiopath + 'gangsta.mp3')
        return self.omx.pause()

    def stop_voice(self):
        return self.omx.quit()

    def _callback_lower(self, gpio, level, tick):

        t = time.time()

        # stop interrupts
        self.cb_lower.cancel()

        # self.data.append('...')

        #print "==== Callback lower reed contact ===="

        timestamps = []

        magnet_count = 0
        one_count = 0
        while True:
            inter_flag = False
            input = 1
            while input:
                input = self.pi.read(gpio)

                # debug
                # self.data.append(input)

                one_count = one_count + 1
                time.sleep(self.T_poll)
            if one_count < self.min_one_count:
                # Interference if no valey interference compensates for it
                # print "Peak Interference suspicion"
                inter_flag = True

            zero_count = 0
            input = 0
            while input == 0:
                input = self.pi.read(gpio)

                # debug
                # self.data.append(input)

                zero_count = zero_count + 1
                time.sleep(self.T_poll)
                if zero_count > self.max_zero_count:
                    # No more consecutive magnets --> activate
                    # interrupts again for next passing of weights
                    break

                elif inter_flag and zero_count >= self.min_zero_count:
                    # No valey interference to compensate for peak interference
                    # check if interference is isolated
                    # print "Peak interference detected on lower contact"
                    if magnet_count == 0:
                        # isolated interference
                        self.cb_lower = self.pi.callback(
                            gpio, pigpio.RISING_EDGE, self._callback_lower)
                        #print "Interference detected"
                        return
                    else:
                        # interference between magnets --> treet ones as zeros
                        zero_count = zero_count + one_count
            if zero_count < self.min_zero_count:
                pass
                # Interference --> continue with first while loop
                # print "Valey Interference detected on lower contact"
                # if inter_flag:
                # print "No peak interference"
            elif zero_count > self.max_zero_count:
                # No more consecutive magnets --> calculate values of one repetition
                magnet_count = magnet_count + 1
                #print "Magnet Count: ", magnet_count
                timestamps.append(t)  # save old timestamp
                #print " Timestamps: ", timestamps

                v = 0
                if magnet_count > 1:
                    for i in range(magnet_count - 1):
                        v = v + self.plate_dist / (timestamps[i + 1] -
                                                   timestamps[i])
                else:
                    print "Only one magnet detected --> cannot determine speed"

                with self.lock_lower:  # save values of one repetition
                    self.lower_weight = self.plate_weight * magnet_count
                    self.lower_speed = v / magnet_count
                    if self.lower_flag:
                        print "flag wasn't read or properly set back to 0"
                    self.lower_flag = 1
                    self.lower_timestamp = timestamps[magnet_count - 1]

                print "End of consecutive magnets"
                # Reactivate interrupt listener
                self.cb_lower = self.pi.callback(gpio, pigpio.RISING_EDGE,
                                                 self._callback_lower)
                break
            else:
                # start of next magnet
                timestamps.append(t)  # save old timestamp
                t = time.time()
                one_count = 0
                magnet_count = magnet_count + 1
                #print "Magnet Count: ", magnet_count

    def _callback_higher(self, gpio, level, tick):
        t = time.time()

        # stop interrupts
        self.cb_higher.cancel()

        self.data.append('...')

        #print "==== Callback higher reed contact ===="

        timestamps = []

        magnet_count = 0
        one_count = 0
        while True:
            inter_flag = False

            input = 1
            while input:
                input = self.pi.read(gpio)

                # debug
                # self.data.append(input)

                one_count = one_count + 1
                time.sleep(self.T_poll)
            if one_count < self.min_one_count:
                # Interference if no valey interference compensates for it
                # print "Peak Interference suspicion"
                inter_flag = True

            zero_count = 0
            input = 0
            while input == 0:
                input = self.pi.read(gpio)

                # debug
                # self.data.append(input)

                zero_count = zero_count + 1
                time.sleep(self.T_poll)
                if zero_count > self.max_zero_count:
                    # No more consecutive magnets --> activate
                    # interrupts again for next passing of weights
                    break
                elif inter_flag and zero_count >= self.min_zero_count:
                    # No valey interference to compensate for peak interference
                    # check if interference is isolated
                    # print "Peak interference detected on higher contact"
                    if magnet_count == 0:
                        # isolated interference
                        self.cb_higher = self.pi.callback(
                            gpio, pigpio.RISING_EDGE, self._callback_higher)
                        #print "Interference detected"
                        return
                    else:
                        # interference between magnets --> treet ones as zeros
                        zero_count = zero_count + one_count
            if zero_count < self.min_zero_count:
                pass
                # Interference --> continue with first while loop
                # print "Valey Interference detected on higher contact"
                # if inter_flag:
                # print "No peak interference"
            elif zero_count > self.max_zero_count:
                # No more consecutive magnets --> calculate values of one repetition
                magnet_count = magnet_count + 1
                #print "Magnet Count: ", magnet_count
                timestamps.append(t)  # save old timestamp
                #print " Timestamps: ", timestamps

                v = 0
                if magnet_count > 1:
                    for i in range(magnet_count - 1):
                        v = v + self.plate_dist / (timestamps[i + 1] -
                                                   timestamps[i])
                else:
                    print "Only one magnet detected --> cannot determine speed"

                with self.lock_higher:  # save values of one repetition
                    self.higher_weight = self.plate_weight * magnet_count
                    self.higher_speed = v / magnet_count
                    if self.higher_flag:
                        print "flag wasn't read or properly set back to 0"
                    self.higher_flag = 1
                    self.higher_timestamp = timestamps[magnet_count - 1]

                #print "End of consecutive magnets"
                # Reactivate interrupt listener
                self.cb_higher = self.pi.callback(gpio, pigpio.RISING_EDGE,
                                                  self._callback_higher)
                break
            else:
                # start of next magnet
                timestamps.append(t)  # save old timestamp
                t = time.time()
                one_count = 0
                magnet_count = magnet_count + 1
                #print "Magnet Count: ", magnet_count

    def stop_listening(self):
        if hasattr(self, 'cb_lower') and hasattr(self, 'cb_higher'):
            self.cb_lower.cancel()
            self.cb_higher.cancel()
        elif hasattr(self, 'cb_lower'):
            self.cb_lower.cancel()
        elif hasattr(self, 'cb_higher'):
            self.cb_higher.cancel()
        else:
            print "No listeners to close"

    def start_listening(self, lowerReedPin=17, higherReedPin=22):
        self.cb_lower = self.pi.callback(self.lowerReedPin, pigpio.RISING_EDGE,
                                         self._callback_lower)
        self.cb_higher = self.pi.callback(self.higherReedPin,
                                          pigpio.RISING_EDGE,
                                          self._callback_higher)

    def get_lower_data(self):
        data = [None] * 4
        with self.lock_lower:
            if self.lower_flag:
                data[0] = True
                data[1] = self.lower_timestamp
                data[2] = self.lower_weight
                data[3] = self.lower_speed
                self.lower_flag = 0
            else:
                data[0] = False

        return data

    def get_higher_data(self):
        data = [None] * 4
        with self.lock_higher:
            if self.higher_flag:
                data[0] = True
                data[1] = self.higher_timestamp
                data[2] = self.higher_weight
                data[3] = self.higher_speed
                self.higher_flag = 0
            else:
                data[0] = False

        return data
Пример #23
0
class tree_player(object):
    """
    control one screen on the "Big Tree display"
    toggle between two different movies according to GPIO input signal
    """
    def __init__(self, gpio_number, movie_1, movie_2):
        self.logger = logging.getLogger('tree_player')
        self.logger.info('starting player')
        self.logger.info('movie 1: {}'.format(movie_1))
        self.logger.info('movie 2: {}'.format(movie_2))
        self.logger.info('GPIO: {} (BCM)'.format(gpio_number))

        self.stop_gpio = 21
        self.logger.info('stop GPIO: {} (BCM)'.format(self.stop_gpio))
        self.control_gpio = gpio_number
        self.movie_1 = movie_1
        self.movie_2 = movie_2
        self.current_state = None
        self.polling_tries = 0
        self.stop_state = 0
        self.stop_tries = 0

        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.control_gpio, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.stop_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        #GPIO.add_event_detect(self.control_gpio, GPIO.BOTH, callback=self.event, bouncetime=300)
        #GPIO.add_event_detect(self.stop_gpio, GPIO.FALLING, callback=self.quit, bouncetime=200)

        #self.movie_1_controller = omxplayer.OMXPlayer(mediafile=self.movie_1, args=r'--loop -b --no-osd', start_playback=False)
        #self.movie_2_controller = omxplayer.OMXPlayer(mediafile=self.movie_2, args=r'--loop -b --no-osd', start_playback=False)

        self.movie_1_controller = OMXPlayer(filename=self.movie_1,
                                            args=['--loop', '-b', '--no-osd'])
        self.movie_2_controller = OMXPlayer(filename=self.movie_2,
                                            args=['--loop', '-b', '--no-osd'])
        sleep(1)
        self.running = True
        self.button_reader_thread = threading.Thread(target=self.button_reader)
        self.button_reader_thread.start()

    def button_reader(self):
        self.logger.info('button_reader started')
        while self.running:
            current_state = self.read_current_buttons_state()
            if current_state != self.current_state and self.polling_tries == 20:
                self.current_state = current_state
                self.main_loop()
            elif current_state != self.current_state and self.polling_tries < 20:
                self.polling_tries += 1
            else:
                self.polling_tries = 1

            stop_state = not GPIO.input(self.stop_gpio)
            if stop_state and self.stop_tries == 50:
                self.quit()
            elif stop_state and self.stop_tries < 50:
                self.stop_tries += 1
            else:
                self.stop_tries = 1

            sleep(0.005)

        self.logger.info('button_reader ended')

    def read_current_buttons_state(self):
        """
        read control_gpio state
        """
        return GPIO.input(self.control_gpio)

    def main_loop(self):
        """
        one iteration of main loop,
        called when input is changed,
        stop one movie, seek to 0 (so next time we start from beginning) and play other movie
        :return:
        """
        current_state = self.current_state
        if current_state:
            self.logger.info('state changed to HIGH, show BAD fruit movie')
            self.movie_2_controller.pause()
            sleep(0.1)
            self.movie_2_controller.set_position(0)
            sleep(0.1)
            self.movie_1_controller.play()

        else:
            self.logger.info('state changed to LOW, show GOOD fruit movie')
            self.movie_1_controller.pause()
            sleep(0.1)
            self.movie_1_controller.set_position(0)
            sleep(0.1)
            self.movie_2_controller.play()
        sleep(0.3)

    def quit(self):
        self.logger.info('in quit()')
        self.running = False
        sleep(0.1)
        GPIO.cleanup()
        self.logger.info('stopping both movies')
        self.movie_1_controller.stop()
        self.movie_2_controller.stop()
        sleep(0.5)
        self.logger.info('closing both players')
        try:
            self.movie_1_controller.quit()
        except Exception as ex:
            self.logger.error('while closing player 1, got ex: {}'.format(ex))

        try:
            self.movie_2_controller.quit()
        except Exception as ex:
            self.logger.error('while closing player 2, got ex: {}'.format(ex))

        sleep(0.5)
        self.logger.info('quit function ended')
Пример #24
0
    time.sleep(0.5)
    subprocess.call('sudo pkill omxplayer', shell=True)


GPIO.add_event_detect(force_stop_gpio_i,
                      GPIO.FALLING,
                      callback=quit_program,
                      bouncetime=100)
logger = logging.getLogger('male_zuccini')

logger.info('creating omxplayer objects')
idle_movie_controller = OMXPlayer(filename=idle_video_file,
                                  args=['--loop', '--no-osd'])
after_movie_controller = OMXPlayer(filename=after_video_file,
                                   args=['--no-osd'])
after_movie_controller.pause()
after_movie_controller.set_position(0)
blink_movie_controller = OMXPlayer(filename=blink_video_file,
                                   args=['--loop', '--no-osd'])
logger.info('finished creating omxplayer objects')


def state_idle():
    logger.info('starting state_idle')
    start_time = time.time()
    idle_movie_controller.play()
    while running:
        if not GPIO.input(male_to_female_i):
            start_time = time.time()
            time.sleep(0.05)
Пример #25
0
    import sys
    import pygame
    from time import sleep
    from omxplayer import OMXPlayer

    pygame.init()
    pygame.display.set_mode([100, 100])
    done = False
    print "initialize pygame window"
    #if (quit == False):
    #omxp = subprocess.Popen(['omxplayer',sound_path])
    omxp = OMXPlayer(sound_path)
    omxp.play()
    print 'Playing Sound'
    #sleep(5)
    omxp.pause()

    while not done:

        for event in pygame.event.get():
            print "for loop getting event"
            if event.type == pygame.QUIT:
                done = True
                print "pygame.QUIT event"
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True
                    omxp.quit()
                    print "escape key pressed"
                elif event.key == pygame.K_F1:
                    if (omxp.playback_status() == "Playing"):
Пример #26
0
class Video(object):
	currentTime = 0;
	startTime = 0;

	player = OMXPlayer(dir_path + "/a.mp3", pause=True);
	
	id = "";
	listId = "";
	state = "";
	info = {};

	def dispstart(self):
		return self.startTime;

	def dispcur(self):
		return self.currentTime;

	def setStartTime(self, time):
		self.startTime = time;

	def setCurrentTime(self, time):
		self.currentTime = time;

	def getCurrentTime(self):
		now = int(time.time());
		self.currentTime = now - self.startTime;
		return self.currentTime;

	def create(self):
		videoToPlay = pafy.new("https://www.youtube.com/watch?v=" + self.info["encrypted_id"]);

		bestaudio = videoToPlay.getbestaudio(preftype="m4a", ftypestrict=True);
		file_name =  dir_path + "/music/" + self.id + ".m4a";
		try :
		   bestaudio.download(file_name);
		except:
		   pass
		self.player.quit()
		self.player = OMXPlayer(file_name, pause=True);
		
		AudioSegment.from_file(file_name).export(dir_path + "/music/" + self.id + ".mp3", format="mp3");
		
		r = requests.post(addr_serv + "/serv", data=str(self.id));
		if r.status_code != 200:
			print(r);
			print("error post to 2nd server");
		else:
			print("postb 2nd ok");
	
	def seek(self, timeValue):
		self.player.set_position(timeValue);
		
	def play(self):
		now = int(time.time());
		self.startTime = now - self.currentTime;  # calculate the starting point
		self.state = "1";

		self.player.play();
		
		
		r = requests.post(addr_serv + "/serv", data=self.state);
		if r.status_code != 200:
			print(r);
			print("error post to 2nd server");
		else:
			print("postb 2nd ok");

	def pause(self):
		self.getCurrentTime();
		self.state = "2";

		self.player.pause();
		
		r = requests.post(addr_serv + "/serv", data=self.state);
		if r.status_code != 200:
			print(r);
			print("error post to 2nd server");
		else:
			print("postb 2nd ok");
		
	def stop(self): # useless for the moment but mayby later...
		self.state = "0";
	
	def volume(self, volume):
		self.player.set_volume(-6000 + volume * 60); #-6000/100 car omx va de -6000 a 0 et volume de 0 a 100
#!/usr/bin/env python2
import os.path
from time import sleep
from omxplayer import OMXPlayer
from smoke_tests import TEST_MEDIA_FILE_1, TEST_MEDIA_FILE_2

player = OMXPlayer(TEST_MEDIA_FILE_1, pause=True)
print("Start playing vid1")
player.play()
sleep(2)
print("Stop playing vid1")
player.pause()
sleep(2)

player.load(TEST_MEDIA_FILE_2, pause=True)
print("Start playing vid2")
player.play()
sleep(2)
print("Stop playing vid2")
player.pause()
sleep(2)

print("Exit")
player.quit()
sleep(1)
Пример #28
0
#!/usr/bin/env python2
import os.path
from time import sleep
from omxplayer import OMXPlayer
from . import TEST_MEDIA_FILE_1, TEST_MEDIA_FILE_2

vid1 = OMXPlayer(TEST_MEDIA_FILE_1)
print("Start playing vid1")
vid1.play()
sleep(2)
print("Stop playing vid1")
vid1.pause()
sleep(2)
print("Exit vid1")
vid1.exit()
sleep(1)

vid2 = OMXPlayer(TEST_MEDIA_FILE_2)
print("Start playing vid2")
vid2.play()
sleep(2)
print("Stop playing vid2")
vid2.pause()
sleep(2)
print("Exit vid2")
vid2.exit()
def basic_func():
##        try:
                print(commands)
                print(commands["play_pause"])
                directory = create_playlist()
                shuffle(directory)
                print ("currently, my playlist is {}".format(directory))
                my_playlist_length = len(directory)
                my_song_index = 0
                my_song = directory[0]
                print ("My song right now is {}".format(my_song))
                player = OMXPlayer(my_song)
                print ("im intalized")
                player.pause()
                my_volume = player.volume()
                while True:

                        if player.position() >= player.duration()-1.5:
                                commands["skip"] = True
                        if commands["play_pause"]:
                                print("pressed")
                                if not player.is_playing():
                                    print ("I was paused, now I'm playing")
                                    player.play()
                                elif player.is_playing():
                                    player.pause()    
                                print (player.duration())
                                print (player.position())
                                commands["play_pause"] = False
                        elif commands["quit"]:
                                print ('im quiting')
                                commands["quit"] = False
                                player.quit()
                                break
                        elif commands["quieter"]:
                                my_volume = my_volume-1000
                                player.set_volume(my_volume)
                                print(my_volume)
                                commands["quieter"] = False
                        elif commands["louder"]:
                                my_volume = player.volume()
                                my_volume = my_volume+1000
                                player.set_volume(my_volume)
                                print(my_volume)
                                commands["louder"] = False
                        elif commands["skip"]:
                                player.quit()
                                my_song_index = (my_song_index + 1)%my_playlist_length
                                if my_song_index == 0:
                                        print ("my playlist was {}".format(directory))
                                        shuffle(directory)
                                        print ("my playlist is now {}".format(directory))
        
                                my_song = directory[my_song_index]
                                player = OMXPlayer(my_song)
                                player.set_volume(my_volume)
                                commands["skip"] = False
                                
                                print ("Now, my_song is {}".format(my_song))
                                

                
##        except:
                GPIO.cleanup()
                player.quit()