Esempio n. 1
0
def play_video():
    db = shelve.open('datastore', 'c')

    video_index = db.get('video_index', 0)
    videos = db.get('videos', [])

    if video_index >= len(videos):
        video_index = 0

    if video_index >= len(videos):
        return

    db['video_index'] = video_index
    db.close()

    print "play " + videos[video_index]

    videofile = os.path.abspath(os.getcwd()) + "/video/" + videos[video_index]

    print videofile

    player = OMXPlayer(videofile, args=['--no-osd', '--no-keys', '-b'])

    player.play()

    while 1:
        try:
            print player.playback_status()
        except:
            print "error end"
            player.quit()
            return
Esempio n. 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)
Esempio n. 3
0
def playVideoGo(video_name, start=0, length=0):
    print "Incoming video request"
    videofile_path = "video/"+ video_name 
    # TODO check is file en with mp4 or mov
    print "video to play: " + videofile_path  
    video = OMXPlayer(videofile_path, pause=True)
   
    # set video clip duration
    if start > 0:
        video.set_position(start)

    # set video clip duration
    if length == 0:
        dur = video.duration()
        durint = int(dur)
        video.play()
        time.sleep(durint)  
    else:
        video.play()
        print length
        time.sleep(length)

    print("Stop playing")
    video.quit()
    return "Video file played, lol"
Esempio n. 4
0
def play_video():
    db = shelve.open('datastore', 'c')

    video_index = db.get('video_index', 0)
    videos = db.get('videos', [])

    if video_index >= len(videos):
        video_index = 0

    if video_index >= len(videos):
        return

    db['video_index'] = video_index
    db.close()

    print "play " + videos[video_index]

    videofile = os.path.abspath(os.getcwd()) + "/video/" + videos[video_index]

    print videofile

    player = OMXPlayer(videofile, args=['--no-osd', '--no-keys', '-b'])

    player.play()

    while 1:
        try:
            print player.playback_status()
        except:
            print "error end"
            player.quit()
            return
Esempio n. 5
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):
             #<Merge>
             global movName
             movName = dictSP[str(self.recData)] + "-" + movName
             if os.path.exists("movs/" + movName + ".mp4") is False:
                 movName = "NA"
             #<Playing>
             print "startPlay"
             player = OMXPlayer("movs/" + movName + ".mp4")
             player.play()
             time.sleep(player.duration() - 5)
             com.Send(int(dictPS.get(dictMA.get(movName, "NA"), "0")))
             time.sleep(5)
             #player.pause()
             #if you got to quit you can't re-open
             player.quit()
             print "endPlay"
         #このあとに静止画を表示するなら、dictMA[movName]
         #<loopTest
         self.forTesCount += 1
         if self.forTesCount % 1000 == 0:
             print "recNOW"
         #loopTest>
         time.sleep(0.01)
Esempio n. 6
0
class OMXPlayerTest(unittest.TestCase):
    def setUp(self):
        self.player = OMXPlayer(MEDIA_FILE_PATH)
        sleep(1)  # Give the player time to start up

    def tearDown(self):
        self.player.quit()
Esempio n. 7
0
    def _play_ba(self, ba_path, stop, time_status, save_file):
        """
        function qui lance une bande-annonce dans omx player
        """
        player = OMXPlayer(ba_path, args=['-o', 'hdmi', '-b', '--no-osd'])
        player.play()

        # affichage d'un ecran noir pour ne pas voir l'ecran de la ba precedente
        # brievement avant le changement d'ecran
        self._display_slide(env_variables.black_image, 1)
        logging.info("ba: %s, status: %s" % (ba_path, player.playback_status()))                        

        # tant que la ba n'est pas fini ou stoppee, on attend
        while True:
            try:
                if player.playback_status() == "Playing" and stop is False and time_status is False:
                    sleep(1)
                    stop = pickle.load(open( save_file, "rb" ))
                    #logging.info("%s, %s, %s" % (player.playback_status(),stop, time_status))  
                else:
                    logging.warn("before player quit")
                    player.quit()
                    # sortie boucle while
                    break
            except DBusException:
                logging.warn("dbus exception")
                # cette exception est levee a la fin de la ba, sortie du while
                break
        return stop
Esempio n. 8
0
def playVideoGo(video_name, start=0, length=0):
    print "Incoming video request"
    videofile_path = "video/" + video_name
    # TODO check is file en with mp4 or mov
    print "video to play: " + videofile_path
    video = OMXPlayer(videofile_path, pause=True)

    # set video clip duration
    if start > 0:
        video.set_position(start)

    # set video clip duration
    if length == 0:
        dur = video.duration()
        durint = int(dur)
        video.play()
        time.sleep(durint)
    else:
        video.play()
        print length
        time.sleep(length)

    print("Stop playing")
    video.quit()
    return "Video file played, lol"
Esempio n. 9
0
class video_and_tag:
    def __init__(self, fl_path):
        self.movie_fl_path = None
        self.channels = None
        self.player = None
        self.movie_pool = None
        self.fl_path = fl_path
        self.play_log = None

    def logging(self, info):
        self.play_log = self.play_log + info

    def get_file_pool(self):
        file_pool = []
        file_box = os.listdir(self.fl_path)
        for item in file_box:
            if item.split('.')[0] == '' or item.split('.')[-1] != 'mp4':  # 这里不能用is not
                continue
            file_pool.append(item)
        file_pool.sort()
        self.movie_pool = file_pool

    def play_movie(self, fl_path):
        self.movie_fl_path = fl_path
        VIDEO_PATH = Path(self.movie_fl_path)
        self.player = OMXPlayer(VIDEO_PATH)

    def stop_movie(self):
        self.player.quit()
Esempio n. 10
0
class OMXPlayerTest(unittest.TestCase):
    MEDIA_FILE_PATH = './media/test_media_1.mp4'

    def setUp(self):
        self.player = OMXPlayer(self.MEDIA_FILE_PATH)

    def tearDown(self):
        self.player.quit()
Esempio n. 11
0
class OMXPlayerTest(unittest.TestCase):
    MEDIA_FILE_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../media/test_media_1.mp4')

    def setUp(self):
        self.player = OMXPlayer(self.MEDIA_FILE_PATH)
        sleep(1) # Give the player time to start up

    def tearDown(self):
        self.player.quit()
Esempio n. 12
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)
Esempio n. 13
0
    def test_exit_event_on_quit(self):
        player = OMXPlayer(MEDIA_FILE_PATH)
        exit_fn = Mock()
        player.exitEvent += exit_fn
        sleep(1)

        player.quit()

        exit_fn.assert_called_once_with(player, -15)
Esempio n. 14
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()
Esempio n. 15
0
def main():

    try:
        player = OMXPlayer(choice(trans_films))

        while True:
            play_film(player, choice(trans_films), duration=1)
            play_film(player, choice(rotate_films), duration=10)
        print "Done."

    except KeyboardInterrupt:
        # Kill the `omxplayer` process gracefully.
        player.quit()
Esempio n. 16
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
Esempio n. 17
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()
Esempio n. 18
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()
Esempio n. 19
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()
Esempio n. 20
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()
Esempio n. 21
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)
Esempio n. 22
0
def play():
    '''
        start the programm
        Returns:
    '''

    print("get video path from config")
    # load config
    video_path = read_config()

    # get mp4 files from video_path
    video_list = read_directory(video_path)

    if video_list:
        for video in video_list:
            print("Play: " + video)
            player = OMXPlayer(video)
            player.play()
            player.quit()
        return "Playlist end"
    else:
        return "There is no valid video in " + video_path
        sleep(5)
Esempio n. 23
0
def voice_object_Out(voice):
    player = OMXPlayer(
        os.path.join(CWD_PATH, 'voice', 'guide_voice', 'this.mp3'))
    time.sleep(0.8)
    player.quit()
    player = OMXPlayer(
        os.path.join(CWD_PATH, 'voice', 'object_voice', voice + '.mp3'))
    time.sleep(1.0)
    player.quit()
    player = OMXPlayer(os.path.join(CWD_PATH, 'voice', 'guide_voice',
                                    'is.mp3'))
    time.sleep(1.0)
    player.quit()
Esempio n. 24
0
    def run(self):
        time_status = False
        stop = False
        save_file = os.path.join(env_variables.home_ba, 'save.p')
        pickle.dump(stop, open( save_file, "wb" ))
        logging.info("in run method")
    
        # tant que l'on a pas appuye sur "stopper les ba", on continue !
        if self.timer_in_seconds is None:
            env_variables.lock.acquire()
            # on joue toutes les bande-annonces une seule fois
            for track in self.ba_file_list:
                # sortie de la boucle for si stop = True
                if stop is True:
                    break

                # lancement de la ba
                player = OMXPlayer(track, args=['-o', 'hdmi', '-b', '--no-osd'])
                player.play()
                
                # affichage d'un ecran noir pour ne pas voir l'ecran de la ba precedente
                # brievement avant le changement d'ecran
                try:
                    return_code = subprocess.call("export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '" + env_variables.black_image +"'", shell=True)
                except Exception as e:
                    logging.error('black image display failed: %s' % str(e))
                sleep(1)
                logging.info("ba: %s, status: %s" % (track, player.playback_status()))

                # tant que la ba n'est pas fini ou stoppee, on attend
                while True:
                    try:
                        if player.playback_status() == "Playing" and stop is False:
                            sleep(1)
                            stop = pickle.load(open( save_file, "rb" ))
                            #logging.info("%s, %s" % (player.playback_status(),stop))  
                        else:
                            logging.warn("before player quit - timer is None")
                            player.quit()
                            # sortie boucle while
                            break
                    except DBusException:
                        # cette exception est levee a la fin de la ba, sortie du while
                        logging.warn("dbus exception - timer is None")
                        break

                    # affichage du display entre deux bande-annonces
                    # recuperation image correspondante a la ba
                    if stop is False and track != env_variables.ba_carte_fidelite:
                        try:
                            image = track.split('.mp4')[0] + '.jpg'
                            logging.info("slide montre: %s" % image)
                            command = "export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '" + image +"'"
                            return_code = subprocess.call(command, shell=True)
                            if return_code == 0:
                                sleep(env_variables.temps_entre_2_ba)
                            else:
                                raise RuntimeError
                        except Exception as e:
                            logging.error("command is:%s" % command)
                            logging.error("display slide return code: %i" % return_code)
                            logging.error('image display failed: %s' % str(e))
            
            env_variables.lock.release()

        else:
            env_variables.lock.acquire()
            # ajouter un check de la valeur de timer
            timeout = time.time() + self.timer_in_seconds

            while stop is False and time_status is False:
                
                for track in self.ba_file_list:

                    # sortie de la boucle for si stop = True
                    if stop or time_status:
                        break

                    # lancement de la ba
                    player = OMXPlayer(track, args=['-o', 'hdmi', '-b', '--no-osd'])
                    player.play()

                    # affichage d'un ecran noir pour ne pas voir l'ecran de la ba precedente
                    # brievement avant le changement d'ecran
                    try:
                        return_code = subprocess.call("export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '" + env_variables.black_image +"'", shell=True)
                    except Exception as e:
                        logging.error('black image display failed: %s' % str(e))
                    sleep(1)
                    logging.info("ba: %s, status: %s" % (track, player.playback_status()))                        

                    # tant que la ba n'est pas fini ou stoppee, on attend
                    while True:
                        try:
                            if player.playback_status() == "Playing" and stop is False and time_status is False:
                                sleep(1)
                                stop = pickle.load(open( save_file, "rb" ))
                                time_status = time.time() > timeout
                                #logging.info("%s, %s, %s" % (player.playback_status(),stop, time_status))  
                            else:
                                logging.warn("before player quit - timer is set")
                                player.quit()
                                # sortie boucle while
                                break
                        except DBusException:
                            logging.warn("dbus exception - timer is set")
                            # cette exception est levee a la fin de la ba, sortie du while
                            break

                    # affichage du display entre deux bande-annonces
                    # recuperation image correspondante a la ba
                    if stop is False and track != env_variables.ba_carte_fidelite:
                        try:
                            image = track.split('.mp4')[0] + '.jpg'
                            logging.info("slide montre: %s" % image)
                            command = "export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '" + image +"'"
                            return_code = subprocess.call(command, shell=True)
                            if return_code == 0:
                                sleep(env_variables.temps_entre_2_ba)
                            else:
                                raise RuntimeError
                        except Exception as e:
                            logging.error("command is:%s" % command)
                            logging.error("display slide return code: %i" % return_code)
                            logging.error('image display failed: %s' % str(e))

            env_variables.lock.release()

            if time_status is True:
                subprocess.call(['sudo', 'shutdown', '-h', 'now'])
Esempio n. 25
0
 def test_load(self):
     player = OMXPlayer(MEDIA_FILE_PATH)
     sleep(1)
     player.load(MEDIA_FILE_PATH)
     sleep(1)
     player.quit()
Esempio n. 26
0
 def test_str_media_file_path(self):
     player = OMXPlayer(str(MEDIA_FILE_PATH))
     sleep(1)
     player.quit()
Esempio n. 27
0
 def test_args_str_constructor(self):
     player = OMXPlayer(MEDIA_FILE_PATH, args='--layer 2 --orientation 90')
     sleep(1)
     player.quit()
Esempio n. 28
0
 def test_args_list_constructor(self):
     player = OMXPlayer(MEDIA_FILE_PATH,
                        args=['--layer', '2', '--orientation', '90'])
     sleep(1)
     player.quit()
Esempio n. 29
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()
Esempio n. 30
0
#!/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

vid1 = OMXPlayer(TEST_MEDIA_FILE_1)
print("Start playing vid1")
sleep(5)

print("Stop playing vid1")
vid1.pause()
sleep(2)

print("Exit vid1")
vid1.quit()
sleep(1)

vid2 = OMXPlayer(TEST_MEDIA_FILE_2)
print("Start playing vid2")
sleep(2)

print("Stop playing vid2")
vid2.pause()
sleep(2)

print("Exit vid2")
vid2.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()
Esempio n. 32
0
    if GPIO.input(up) == 0:  #set in interrupt
        if playerA.is_playing() == True:
            playerB.set_video_pos(200, 200, 627, 440)
            playerB.play()
        elif playerB.is_playing == True:
            playerC.set_video_pos(200, 200, 627, 440)
            playerC.play()
        else:
            playerA.set_video_pos(200, 200, 627, 440)
            playerA.play()

    if GPIO.input(down) == 0:  # set in interrupt
        if playerC.is_playing() == True:
            playerB.play()
            playerB.set_video_pos(200, 200, 627, 440)
        elif playerB.is_playing == True:
            playerA.play()
            playerA.set_video_pos(200, 200, 627, 440)
        else:
            playerC.play()
            playerC.set_video_pos(200, 200, 627, 440)

    if GPIO.input(enter) == 0:
        if playerA.is_playing() == True:
            playerA.quit()
        elif playerB.is_playing() == True:
            playerB.quit()
        elif playerC.is_playing() == True:
            playerC.quit()

GPIO.cleanup()
Esempio n. 33
0
#!/usr/bin/env python2
from omxplayer import OMXPlayer
from time import sleep
from smoke_tests import TEST_STREAM_FILE_1

print("Streaming " + TEST_STREAM_FILE_1)
print("Starting OMXPlayer")
vid1 = OMXPlayer(TEST_STREAM_FILE_1)
for i in xrange(0, 10):
    print("sleeping %s" % i)
    sleep(1)
print("Pause for 2 seconds")
vid1.pause()
sleep(2)
print("Exiting")
vid1.quit()
Esempio n. 34
0
File: KuBo.py Progetto: mguy02/kubo
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
Esempio n. 35
0
    200, 200, 627,
    440)  #video files are ?854 × 480px.? Divide with two + x1 and y1

while player.is_playing():
    #TODO: create a way for videos to be in a mill. Look over c# prg.

    #player = OMXPlayer(default, args=['-o', 'local'], )
    #player.set_video_pos(200, 200, 627, 440)

    if GPIO.input(up) == 0:
        player.load(vida)
        player.set_video_pos(200, 200, 627, 440)
        print("button1 pushed")
        player.play()
        #sleep(5)

    elif GPIO.input(down) == 0:
        player.load(vidb)
        player.set_video_pos(200, 200, 627, 440)
        print("button2 pushed")
        player.play()
        #sleep(5)

    elif GPIO.input(enter) == 0:
        player.quit()
        loop = False

# Kill the `omxplayer` process gracefully.
player.quit()
GPIO.cleanup()
Esempio n. 36
0
class VideoOmxplayerPlugin(Plugin):
    video_extensions = {
        '.avi', '.flv', '.wmv', '.mov', '.mp4', '.m4v', '.mpg', '.mpeg', '.rm',
        '.swf', '.vob'
    }

    default_torrent_ports = [6881, 6891]
    torrent_state = {}

    def __init__(self,
                 args=[],
                 media_dirs=[],
                 download_dir=None,
                 torrent_ports=[],
                 *argv,
                 **kwargs):
        super().__init__(*argv, **kwargs)

        self.args = args
        self.media_dirs = set(
            filter(
                lambda _: os.path.isdir(_),
                map(lambda _: os.path.abspath(os.path.expanduser(_)),
                    media_dirs)))

        if download_dir:
            self.download_dir = os.path.abspath(
                os.path.expanduser(download_dir))
            if not os.path.isdir(self.download_dir):
                raise RuntimeError(
                    'download_dir [{}] is not a valid directory'.format(
                        self.download_dir))

            self.media_dirs.add(self.download_dir)

        self.player = None
        self.videos_queue = []
        self.torrent_ports = torrent_ports if torrent_ports else self.default_torrent_ports

    def play(self, resource):
        if resource.startswith('youtube:') \
                or resource.startswith('https://www.youtube.com/watch?v='):
            resource = self._get_youtube_content(resource)
        elif resource.startswith('magnet:?'):
            response = self.download_torrent(resource)
            resources = response.output
            if resources:
                self.videos_queue = resources
                resource = self.videos_queue.pop(0)
            else:
                error = 'Unable to download torrent {}'.format(resource)
                logging.warning(error)
                return Response(errors=[error])

        logging.info('Playing {}'.format(resource))

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

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

        return self.status()

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

    def stop(self):
        if self.player:
            self.player.stop()
            self.player.quit()
            self.player = None

        return self.status()

    def voldown(self):
        if self.player:
            self.player.set_volume(max(-6000, self.player.volume() - 1000))
        return self.status()

    def volup(self):
        if self.player:
            self.player.set_volume(min(0, self.player.volume() + 1000))
        return self.status()

    def back(self):
        if self.player:
            self.player.seek(-30)
        return self.status()

    def forward(self):
        if self.player:
            self.player.seek(+30)
        return self.status()

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

        if self.videos_queue:
            video = self.videos_queue.pop(0)
            return self.play(video)

        return Response(output={'status': 'no media'}, errors=[])

    def hide_subtitles(self):
        if self.player: self.player.hide_subtitles()
        return self.status()

    def hide_video(self):
        if self.player: self.player.hide_video()
        return self.status()

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

    def load(self, source, pause=False):
        if self.player: self.player.load(source, pause)
        return self.status()

    def metadata(self):
        if self.player: return Response(output=self.player.metadata())
        return self.status()

    def mute(self):
        if self.player: self.player.mute()
        return self.status()

    def unmute(self):
        if self.player: self.player.unmute()
        return self.status()

    def seek(self, relative_position):
        if self.player: self.player.seek(relative_position)
        return self.status()

    def set_position(self, position):
        if self.player: self.player.set_seek(position)
        return self.status()

    def set_volume(self, volume):
        # Transform a [0,100] value to an OMXPlayer volume in [-6000,0]
        volume = 60.0 * volume - 6000
        if self.player: self.player.set_volume(volume)
        return self.status()

    def status(self):
        state = PlayerState.STOP.value

        if self.player:
            state = self.player.playback_status().lower()
            if state == 'playing': state = PlayerState.PLAY.value
            elif state == 'stopped': state = PlayerState.STOP.value
            elif state == 'paused': state = PlayerState.PAUSE.value

            return Response(
                output=json.dumps({
                    'source': self.player.get_source(),
                    'state': state,
                    'volume': self.player.volume(),
                    'elapsed': self.player.position(),
                    'duration': self.player.duration(),
                    'width': self.player.width(),
                    'height': self.player.height(),
                }))
        else:
            return Response(
                output=json.dumps({'state': PlayerState.STOP.value}))

    def on_play(self):
        def _f(player):
            get_bus().post(VideoPlayEvent(video=self.player.get_source()))

        return _f

    def on_pause(self):
        def _f(player):
            get_bus().post(VideoPauseEvent(video=self.player.get_source()))

        return _f

    def on_stop(self):
        def _f(player):
            get_bus().post(VideoStopEvent())

        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()

    def search(self, query, types=None, queue_results=False, autoplay=False):
        results = []
        if types is None:
            types = {'youtube', 'file', 'torrent'}

        if 'file' in types:
            file_results = self.file_search(query).output
            results.extend(file_results)

        if 'torrent' in types:
            torrent_results = self.torrent_search(query).output
            results.extend(torrent_results)

        if 'youtube' in types:
            yt_results = self.youtube_search(query).output
            results.extend(yt_results)

        if results:
            if queue_results:
                self.videos_queue = [_['url'] for _ in results]
                if autoplay:
                    self.play(self.videos_queue.pop(0))
            elif autoplay:
                self.play(results[0]['url'])

        return Response(output=results)

    @classmethod
    def _is_video_file(cls, filename):
        is_video = False
        for ext in cls.video_extensions:
            if filename.lower().endswith(ext):
                is_video = True
                break

        return is_video

    def file_search(self, query):
        results = []
        query_tokens = [_.lower() for _ in re.split('\s+', query.strip())]

        for media_dir in self.media_dirs:
            logging.info('Scanning {} for "{}"'.format(media_dir, query))
            for path, dirs, files in os.walk(media_dir):
                for f in files:
                    if not self._is_video_file(f):
                        continue

                    matches_query = True
                    for token in query_tokens:
                        if token not in f.lower():
                            matches_query = False
                            break

                    if not matches_query:
                        continue

                    results.append({
                        'url': 'file://' + path + os.sep + f,
                        'title': f,
                    })

        return Response(output=results)

    def youtube_search(self, query):
        logging.info('Searching YouTube for "{}"'.format(query))

        query = urllib.parse.quote(query)
        url = "https://www.youtube.com/results?search_query=" + query
        response = urllib.request.urlopen(url)
        html = response.read()
        soup = BeautifulSoup(html, 'lxml')
        results = []

        for vid in soup.findAll(attrs={'class': 'yt-uix-tile-link'}):
            m = re.match('(/watch\?v=[^&]+)', vid['href'])
            if m:
                results.append({
                    'url': 'https://www.youtube.com' + m.group(1),
                    'title': vid['title'],
                })

        logging.info(
            '{} YouTube video results for the search query "{}"'.format(
                len(results), query))

        return Response(output=results)

    @classmethod
    def _get_youtube_content(cls, url):
        m = re.match('youtube:video:(.*)', url)
        if m: url = 'https://www.youtube.com/watch?v={}'.format(m.group(1))

        proc = subprocess.Popen(['youtube-dl', '-f', 'best', '-g', url],
                                stdout=subprocess.PIPE)

        return proc.stdout.read().decode("utf-8", "strict")[:-1]

    def torrent_search(self, query):
        logging.info(
            'Searching matching movie torrents for "{}"'.format(query))
        request = urllib.request.urlopen(
            urllib.request.Request(
                'https://api.apidomain.info/list?' +
                urllib.parse.urlencode({
                    'sort': 'relevance',
                    'quality': '720p,1080p,3d',
                    'page': 1,
                    'keywords': query,
                }),
                headers={
                    'User-Agent':
                    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
                    '(KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
                }))

        results = [{
            'url': _['items'][0]['torrent_magnet'],
            'title': _['title'],
        } for _ in json.loads(request.read())['MovieList']]

        return Response(output=results)

    def download_torrent(self, magnet):
        import libtorrent as lt

        if not self.download_dir:
            raise RuntimeError(
                'No download_dir specified in video.omxplayer configuration')

        ses = lt.session()
        ses.listen_on(*self.torrent_ports)

        info = lt.parse_magnet_uri(magnet)
        logging.info('Downloading "{}" to "{}" from [{}]'.format(
            info['name'], self.download_dir, magnet))

        params = {
            'save_path': self.download_dir,
            'storage_mode': lt.storage_mode_t.storage_mode_sparse,
        }

        transfer = lt.add_magnet_uri(ses, magnet, params)
        status = transfer.status()
        files = []

        self.torrent_state = {
            'url': magnet,
            'title': info['name'],
        }

        while (not status.is_seeding):
            status = transfer.status()
            torrent_file = transfer.torrent_file()
            if torrent_file:
                files = [
                    os.path.join(self.download_dir,
                                 torrent_file.files().file_path(i))
                    for i in range(0,
                                   torrent_file.files().num_files())
                    if self._is_video_file(torrent_file.files().file_name(i))
                ]

            self.torrent_state['progress'] = 100 * status.progress
            self.torrent_state['download_rate'] = status.download_rate
            self.torrent_state['upload_rate'] = status.upload_rate
            self.torrent_state['num_peers'] = status.num_peers
            self.torrent_state['state'] = status.state

            logging.info(
                ('Torrent download: {:.2f}% complete (down: {:.1f} kb/s ' +
                 'up: {:.1f} kB/s peers: {} state: {})').format(
                     status.progress * 100, status.download_rate / 1000,
                     status.upload_rate / 1000, status.num_peers,
                     status.state))

            time.sleep(5)

        return Response(output=files)

    def get_torrent_state(self):
        return self.torrent_state