Beispiel #1
1
def prevSong():
    global path
    global currentSongIndex
    if(currentSongIndex < 0 and globalPlayer.is_playing()):
        currentSongIndex = len(songList)
    else:
        currentSongIndex = currentSongIndex - 1

    globalPlayer = OMXPlayer(path + songList[currentSongIndex])
    globalPlayer.play()
Beispiel #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)
class Controller(object):
    def __init__(self):
        pass

    def check_new_files(self):
        '''
        check new files from _DIR
        '''
        self._files = []
        for files in os.listdir(_DIR):
            if files.endswith(('wmv', 'mp4', 'mov', 'avi')):
               self._files.append(os.path.join(_DIR, files))
            else:
                pass

    def play_files(self):
        '''
        Play all the files sequentially
        '''
        self.idx = 0
        while True:
            # Loop over list of files
            self.current_file = self._files[self.idx]
            self.idx = (self.idx + 1) % len(self._files)
            self.next_file = self._files[self.idx]
            # Play files one after the other
            self.player(self.current_file)
            
    def player(self, current_file):
        print(current_file,'\n','\tPlaying')
        # Set output window size
        self.omx = OMXPlayer(current_file, args=["--win", " 0,0,640,480"])
        self.omx.play()
        try:
            self.omx.set_position(15.0)
            while True:
                try:
                    if not(self.omx.playback_status()):
                        # If file ended.. stop playback
                        print('\n\tStopped\n')
                        self.omx.stop()
                        break
                    
                    else:
                        # Print time elapsed
                        print('\r\t','{0:.2f}'.format(self.omx.position()),
                              '/', '{0:.2f}'.format(self.omx.duration())+
                              ' seconds', end = ''),
                        sys.stdout.flush()
                    
                except Exception, e:
                    # dBUS exception for file that 
                    # finished playing. Ignore!
                    pass

        except KeyboardInterrupt, e:
            # Catch Ctrl+C and stop playing
            # current file
            print('Stopping Playback..', e)
            self.omx.stop()
Beispiel #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
Beispiel #5
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")
Beispiel #6
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"
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
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")
Beispiel #9
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)
Beispiel #10
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
Beispiel #11
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"
Beispiel #12
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()
Beispiel #13
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)
Beispiel #14
0
def prevSong():
    global path
    global currentSongIndex
    if (currentSongIndex < 0 and globalPlayer.is_playing()):
        currentSongIndex = len(songList)
    else:
        currentSongIndex = currentSongIndex - 1

    globalPlayer = OMXPlayer(path + songList[currentSongIndex])
    globalPlayer.play()
Beispiel #15
0
def nextSong():
    global currentSongIndex
    global path
    if (currentSongIndex >= len(songList) and globalPlayer.is_playing()):
        currentSongIndex = 0
    else:
        currentSongIndex = currentSongIndex + 1

    globalPlayer = OMXPlayer(path + songList[currentSongIndex])
    globalPlayer.play()
Beispiel #16
0
def nextSong():
    global currentSongIndex
    global path
    if(currentSongIndex >= len(songList) and globalPlayer.is_playing()):
        currentSongIndex = 0
    else:
        currentSongIndex = currentSongIndex + 1

    globalPlayer = OMXPlayer(path + songList[currentSongIndex])
    globalPlayer.play()
Beispiel #17
0
class foo(OMXPlayer):
  def __init__(self, file):
    self.file = file
    self.player = OMXPlayer('black.mp4')
    #self.player.pause()

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

  def load(self):
    self.player.load(self.file)
Beispiel #18
0
def playVid(video_file):
    global video
    if video.playback_status() == "Paused":
        if (video_file != video.get_filename()):
            video.quit()
            video = OMXPlayer(video_file, args=['-b'])
            print video_file + "loaded"
        video.play()
        start_new_thread(stopListener, ())
        print "Playing " + video_file + " at " + str(datetime.datetime.now())
    else:  #already playing, must have been forced to play
        print "Already Playing - " + str(datetime.datetime.now())
def play_mp3(p_name_n):
    try:
        player = OMXPlayer("{0}".format(p_name_n))
        player.play()
        #player.quit()
        #con.write(b'comp')
        #print("send")
        #time.sleep(0.625)
        #con.write(b'0000')
        print("init")
        #time.sleep(0.625)
    except:
        pass
Beispiel #20
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
def route_player_open_new_file(request, file):
    global current_thing_playing
    path_to_file = file_container.match_hash_for_file(file)
    current_thing_playing = file_container.match_hash_for_file_name(file)
    global player
    if player is not None:
        player.quit()
	kill_player_pids(dbus_daemon_handle)
        player = OMXPlayer(path_to_file)
	player.play()
    else:
    	player = OMXPlayer(path_to_file)
    	player.play()
    return path_to_file
Beispiel #22
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)
Beispiel #23
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()
Beispiel #24
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()
Beispiel #25
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")
Beispiel #26
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()
Beispiel #27
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()
Beispiel #28
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()
Beispiel #29
0
def omxplayerRestart(file):
    global gl_omxplayer
    try:
        alpha = int(spinAlpha.get())
    except:
        alpha = 210
    if alpha > 255:
        alpha = 255
    elif alpha < 0:
        alpha = 0
    spinAlpha.delete(0, tkinter.END)
    spinAlpha.insert(0, alpha)
    # 1. Prüfen, ob omxplayer bereits läuft:
    if not gl_omxplayer is None:
        gl_omxplayer.stop()
        gl_omxplayer.quit()
        gl_omxplayer = None
        try:
            bauwong.update() # DoEvents
        except:
            pass
    # 2. Neue omxplayer-Instanz erstellen und die Wiedergabe der angegebenen Datei starten:
    playing = False
    starttim = time.time() # Vergangene Sekunden seit dem 01. Januar 1970
    while playing == False:
        # Diese Schleife ist notwendig, da der omxplayer manchmal
        # beim Start eines Titels "Zeile 67:  <pid> Abgebrochen" meldet.
        # In diesem Falle würde sofort zum übernächsten Titel gesprungen werden,
        # was für den unbedarften Benutzer nicht nachvollziehbar ist!
        gl_omxplayer = OMXPlayer(file, ['--alpha', str(alpha)])
        if gl_omxplayer is None:
            playing = False
        else:
            txt = gl_omxplayer.playback_status()
            playing = txt == "Playing" or txt == "Paused"
            gl_omxplayer.play()
            #gl_omxplayer.set_position(0.0) # Sofort mit voller Lautstärke beginnen, kein Fading!
        # Timeout berücksichtigen:    
        tim = time.time()
        if tim - starttim >= 2.5:
            playing = True # Schleife immer verlassen, wenn die Datei nach 2,5s immer noch nicht abgespielt wird
        time.sleep(0.1)
    updateButPlayPause()    
Beispiel #30
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)
Beispiel #31
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)
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)
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()
Beispiel #34
0
#All Gpio's as input and pull up
GPIO.setup(up, GPIO.IN, pull_up_down=GPIO.PUD_UP
           )  # Set button "up" as input and Activate pull up resistor
GPIO.setup(down, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(enter, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#All players are playing at the same time!?! HOW TO FIX?
playerA = OMXPlayer('/home/pi/Desktop/video/ai.mp4',
                    args=['-o', 'local', '--loop'])
playerB = OMXPlayer('/home/pi/Desktop/video/Culture4Fun.mp4',
                    args=['-o', 'local', '--loop'])
playerC = OMXPlayer('/home/pi/Desktop/video/MT.mp4',
                    args=['-o', 'local', '--loop'])

playerA.play()
playerA.set_video_pos(200, 200, 627, 440)

while True:
    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
Beispiel #35
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'])
Beispiel #36
0
player = OMXPlayer(default, args=['-o', 'local', '--loop'])
player.set_video_pos(
    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()
class RPiMediaPlayerController(NSWindowController):

    audio_formats = ['mp3','mpa','flac','ogg','wav','wma','m4a']
    video_formats = ['avi','wmv','mpg','mpeg','mp4','mkv','m4v','m2v','mpv','ogv','flv','mov'] 
    media_patterns = re.compile(".*\.("+"|".join(audio_formats+video_formats)+")$", re.IGNORECASE)

    hostnameField = objc.IBOutlet()
    usernameField = objc.IBOutlet()
    passwordField = objc.IBOutlet()
    filenameField = objc.IBOutlet()
    messageField  = objc.IBOutlet()
    nowPlayingField = objc.IBOutlet()

    playButton = objc.IBOutlet()
    fButton    = objc.IBOutlet()
    ffButton   = objc.IBOutlet()
    bButton    = objc.IBOutlet()
    bbButton   = objc.IBOutlet()
    stopButton = objc.IBOutlet()
    volupButton   = objc.IBOutlet()
    voldownButton = objc.IBOutlet()
    
    uploadButton = objc.IBOutlet()

    playButtons = (
            'playButton',
            'fButton',
            'ffButton',
            'bButton',
            'bbButton',
            'stopButton',
            'volupButton',
            'voldownButton',
            )
    
    def setPlayButtons(self,enable):
        for button in self.playButtons:
            eval('self.{}'.format(button)).setEnabled_(enable)

    def scp_and_play(self):
        self.scp_handler = SCPHandler(self.hostname,self.username,self.password)
        self.remote_file = "/tmp/{}".format(self.filename.split("/")[-1])
        self.scp_handler.scp(self.filename,self.remote_file)
        filename = self.filename.split("/")[-1].replace("\\","")
        self.messageField.setStringValue_("Upload starting...")
        time.sleep(0.5)
        while self.scp_handler.progress != 100:
            time.sleep(0.1)
            message = "Uploading {filename} to {remote}\nProgress: {p}%".format(
                                filename=filename,
                                remote=self.hostname,
                                p=self.scp_handler.progress)
            self.messageField.setStringValue_(message)
        
        message = "Uploading {filename} to {remote}\nProgress: Done".format(
                                filename=filename,
                                remote=self.hostname)
        self.messageField.setStringValue_(message)
        
        # start player
        self.omxplayer = OMXPlayer(self.hostname, self.username, self.password)
        self.omxplayer.play(self.remote_file)
        self.nowPlayingField.setStringValue_("Currently Playing:\n{}".format(filename))
        self.setPlayButtons(True)

        # poll for status of video
        # (don't start polling until omxplayer has had some time to get started)
        time.sleep(10)
        while self.omxplayer.playing:
            time.sleep(1)

        # reset when playing is done
        self.setPlayButtons(False)
        self.uploadButton.setEnabled_(True)
        self.nowPlayingField.setStringValue_("Nothing playing")

    def windowDidLoad(self):
        NSWindowController.windowDidLoad(self)
        self.setPlayButtons(False)

    @objc.IBAction
    def upload_(self, sender):
        self.hostname = self.hostnameField.stringValue()
        self.username = self.usernameField.stringValue()
        self.password = self.passwordField.stringValue()
        self.filename = self.filenameField.stringValue()
        if not os.path.isfile(self.filename):
            self.messageField.setStringValue_("File not found.")
            return
        if not self.media_patterns.match(self.filename):
            self.messageField.setStringValue_("Please only provide audio or video files")
            return
        self.uploadButton.setEnabled_(False)
        self.filename = string_to_path(self.filename)
        scp_and_play_thread = Thread(target=self.scp_and_play, args=())
        scp_and_play_thread.daemon = True
        scp_and_play_thread.start()
    
    @objc.IBAction
    def playpause_(self, sender):
        self.omxplayer.toggle_play()

    @objc.IBAction
    def f_(self, sender):
        self.omxplayer.f()

    @objc.IBAction
    def ff_(self, sender):
        self.omxplayer.ff()

    @objc.IBAction
    def b_(self, sender):
        self.omxplayer.b()

    @objc.IBAction
    def bb_(self, sender):
        self.omxplayer.bb()

    @objc.IBAction
    def volup_(self, sender):
        self.omxplayer.volup()

    @objc.IBAction
    def voldown_(self, sender):
        self.omxplayer.voldown()

    @objc.IBAction
    def stop_(self, sender):
        self.omxplayer.close()
        self.setPlayButtons(False)
        self.uploadButton.setEnabled_(True)
        self.nowPlayingField.setStringValue_("Nothing playing")
Beispiel #38
0
import time
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")
Beispiel #39
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()
	def do_POST(self):
		global player
		global home_path

		jsonData = json.loads(self.rfile.read(int(self.headers.getheader('content-length'))))

		print 'Data received from phone : '
		print jsonData

		command = jsonData['command'];
		if command == 'pause' and 'player' in globals():
			player.pause()
		elif command == 'seek_backward' and 'player' in globals():
			player.action(19)
		elif command == 'seek_forward' and 'player' in globals():
			player.action(20)
		elif command == 'seek_fast_backward' and 'player' in globals():
			player.action(21)
		elif command == 'seek_fast_forward' and 'player' in globals():
			player.action(22)
		elif command == 'previous_audio_stream' and 'player' in globals():
			player.action(6)
		elif command == 'next_audio_stream' and 'player' in globals():
			player.action(7)
		elif command == 'previous_subtitle_stream' and 'player' in globals():
			player.action(10)
		elif command == 'next_subtitle_stream' and 'player' in globals():
			player.action(11)
		elif command == 'decrease_subtitle_delay' and 'player' in globals():
			player.action(13)
		elif command == 'increase_subtitle_delay' and 'player' in globals():
			player.action(14)
		elif command == 'stop' and 'player' in globals():
			player.stop()
			player.quit()
			del player
		elif command == 'delete_file':
			os.remove(jsonData['path'])
		elif command == 'delete_folder':
			shutil.rmtree(jsonData['path'])
		elif command == 'poweroff':
			call(['sudo', 'poweroff'])
		elif command == 'reboot':
			call(['sudo', 'reboot'])
		elif command == 'play':
			if 'player' in globals():
				player.stop()
				player.quit()

			player = OMXPlayer(jsonData['path'], args=['-b'])
			player.play()
		elif command == 'is_playing':
			if 'player' in globals():
				SendResponse(self, {'command': command, 'path': player.get_filename()})
			else:
				SendResponse(self, {'command': command, 'path': ''})

		elif command == 'list_dir':
			path = jsonData['path'] if 'path' in jsonData else home_path

			files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and os.path.splitext(f)[1] in SUPPORTED_FORMATS]
			dirs = [f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]

			files.sort()
			dirs.sort()

			SendResponse(self, {'command': command, 'path': path, 'files': files, 'dirs': dirs})
Beispiel #41
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
Beispiel #42
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()
Beispiel #43
0

if __name__ == "__main__":
    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()