Ejemplo n.º 1
0
Archivo: lmf7.py Proyecto: kkdds/lmf2bk
def video(request):
    global omx,qviv
    global stapwd,setpwd,softPath

    po = yield from request.post()
    #print(po)
    #yield from playv(request)
    if po['p'] == stapwd:
        if po['m'] == 'play':        
            omx = OMXPlayer(softPath+'Videos/'+po['d']+'.mp4')
            tbody= '{"a":"video","b":"play"}'
            while omx._VOF:
                yield from asyncio.sleep(0.5)
            qviv=QIV(softPath+'/'+po['i'])

        elif po['m'] == 'stop':        
            omx.stop()
            tbody= '{"a":"video","b":"stop"}'
            qviv=QIV(softPath+'/'+po['i'])
        elif po['m'] == 'pause':        
            omx.toggle_pause()
            tbody= '{"a":"video","b":"pause"}'
    else:
        tbody= '{"p":"error"}'
        
    print(tbody)
    return web.Response(headers='' ,body=tbody.encode('utf-8'))
Ejemplo n.º 2
0
Archivo: lmf7.py Proyecto: kkdds/lmf
def video(request):
    global omx
	#,qviv
    global stapwd,setpwd,softPath

    po = yield from request.post()
    #print(po)
    if po['p'] == stapwd:
        if po['m'] == 'play':
            #print('video play...')    
            omx = OMXPlayer(softPath+'Videos/'+po['d']+'.mp4',softPath+po['i'])
            tbody= '{"a":"video","b":"play"}'

        elif po['m'] == 'stop':        
            omx.stop()
            tbody= '{"a":"video","b":"stop"}'

        elif po['m'] == 'pause':        
            omx.toggle_pause()
            tbody= '{"a":"video","b":"pause"}'
    else:
        tbody= '{"p":"error"}'
        
    print(tbody)
    return web.Response(headers='' ,body=tbody.encode('utf-8'))
Ejemplo n.º 3
0
 def __init__(self, video):
     self.video = video
     screenWidth, screenHeight = getScreenSize()
     if sys.platform == 'darwin':
         self.player = MPlayerX(self.video, screenWidth, screenHeight)
     else:
         self.player = OMXPlayer(self.video, screenWidth, screenHeight)
     self.from_position = video.progress
def playVideo(fileName, db):
    try:
        p = OMXPlayer(fileName)
        p.toggle_pause()
    except:
        print "problem playing video"
        p = None
    return p
Ejemplo n.º 5
0
Archivo: tv.py Proyecto: emi420/undertv
class TV:

    def __init__(self):
        self.directory = settings['VIDEO_PATH']
        self.playpath = None
        self.waitingvideo = None
        self.video = None
        self.files = []

        for file in os.listdir(self.directory):
            if file.endswith(".mp4"):
                self.files.append(file)

        T_positionChecker = threading.Thread(target=self.positionChecker)
        T_positionChecker.daemon = True                           
        T_positionChecker.start()   

    def random(self):
        episode = random.choice(self.files)
        self.playpath = self.directory + episode
        print "Play " + self.playpath
        if self.video:
            self.stop()
        self.video = OMXPlayer(self.playpath,  '-o hdmi -b', start_playback=True) 

    def waiting(self):
        self.waitingvideo = OMXPlayer(settings['VIDEO_WAITING_PATH'], '-o hdmi -b', start_playback=True) 

    def stop(self):
        self.video.stop()
        self.video = None
        cmd = 'pkill -9 -f "/usr/bin/omxplayer.bin"'
        os.system(cmd)

    def positionChecker(self):
        if not settings['CONTINUOUS_PLAYBACK']:            
            while True:
                if self.video:
                    if self.video.finished:
                        self.video = None
                    if self.waitingvideo and not self.waitingvideo.paused:
                        self.waitingvideo.stop()
                        self.waitingvideo = None

                else:
                   if not self.waitingvideo:
                        self.waitingvideo = OMXPlayer(settings['VIDEO_WAITING_PATH'], '-o hdmi -b --loop', start_playback=True) 

                sleep(0.5)
        else:

            while True:
                if self.video and self.video.finished:
                    self.video = None
                    self.random()
                sleep(0.5)
Ejemplo n.º 6
0
 def play(self, disc, track):
     if not self.file_exists(disc, track):
         return False
     self.musicQueue.append(song(self.musicDir, disc, track))
     if self.currentSong is None:
         self.currentSong = OMXPlayer(self.musicQueue[0].getFile(),
                                      self.next_song,
                                      start_playback=True)
         self.setDisplayCallback(self.musicQueue[0].getString())
     return True
Ejemplo n.º 7
0
class MusicHandler(object):
    def __init__(self, music_dir, set_display_callback):
        self.musicQueue = []
        self.musicDir = music_dir
        self.currentSong = None
        self.setDisplayCallback = set_display_callback

    def file_exists(self, disc, track):
        return os.path.isfile(self.musicDir + '/' + str(disc) + '/' +
                              str(track) + '.mp3')

    def play(self, disc, track):
        if not self.file_exists(disc, track):
            return False
        self.musicQueue.append(song(self.musicDir, disc, track))
        if self.currentSong is None:
            self.currentSong = OMXPlayer(self.musicQueue[0].getFile(),
                                         self.next_song,
                                         start_playback=True)
            self.setDisplayCallback(self.musicQueue[0].getString())
        return True

    def next_song(self):
        if self.currentSong is None:
            self.currentSong = 'Yo Mama'
        if len(self.musicQueue) == 1:
            tmp = self.musicQueue[0].getDiscTrack()
            while not self.play(tmp[0], tmp[1] + 1):
                if tmp[0] >= 99:
                    tmp = 0, -1
                else:
                    tmp = tmp[0] + 1, -1
        self.musicQueue.pop(0)
        self.currentSong = OMXPlayer(self.musicQueue[0].getFile(),
                                     self.next_song,
                                     start_playback=True)
        self.setDisplayCallback(self.musicQueue[0].getString())

    def stop(self):
        print('Stopping Music player')
        if self.currentSong is not None:
            self.currentSong.stop()
            self.currentSong = None

    def isSongPlaying(self):
        return self.currentSong is not None

    def isQueueEmpty(self):
        return len(self.musicQueue) == 0
Ejemplo n.º 8
0
def playFile(args):
    global player
    if player:
        print "player already launched!"
        return
    print "launching OMXPlayer"
    player = OMXPlayer(args["file"], args["args"])
    # The player will initially be paused
    if args.has_key("mute") and args["mute"]:
        print "we need to mute"
        player.toggle_mute()
    if args.has_key("vol"):
        print "setting volume to %d" % args["vol"]
        player.set_vol(args["vol"])
    print "playFile exit"
Ejemplo n.º 9
0
 def next_song(self):
     if self.currentSong is None:
         self.currentSong = 'Yo Mama'
     if len(self.musicQueue) == 1:
         tmp = self.musicQueue[0].getDiscTrack()
         while not self.play(tmp[0], tmp[1] + 1):
             if tmp[0] >= 99:
                 tmp = 0, -1
             else:
                 tmp = tmp[0] + 1, -1
     self.musicQueue.pop(0)
     self.currentSong = OMXPlayer(self.musicQueue[0].getFile(),
                                  self.next_song,
                                  start_playback=True)
     self.setDisplayCallback(self.musicQueue[0].getString())
Ejemplo n.º 10
0
Archivo: tv.py Proyecto: emi420/undertv
 def random(self):
     episode = random.choice(self.files)
     self.playpath = self.directory + episode
     print "Play " + self.playpath
     if self.video:
         self.stop()
     self.video = OMXPlayer(self.playpath,  '-o hdmi -b', start_playback=True) 
def start_video(video_path):
    """Start playing a video, stopping any that is already going"""
    kill_video()
    global PLAYER
    print('starting video: %s' % (video_path))
    PLAYER = OMXPlayer(video_path)
    return
Ejemplo n.º 12
0
    def get(self):
        global _current_player
        action = self.get_argument("action")
        print(action, _current_player)

        if action == "play":
            location = self.get_location()
            if _current_player is not None:
                _current_player.stop()

            _current_player = OMXPlayer(location, args="-p")
            _current_player.play()

        elif action == "download":
            if location.startswith("http"):
                self.redirect(self.get_location())
        else:
            if _current_player is not None:
                getattr(_current_player, action)()
Ejemplo n.º 13
0
 def PlayMedia(self, fullpath, tag, unknown1, unknown2, unknown3):
     print "---"
     print fullpath
     print tag
     f = urllib2.urlopen(fullpath)
     s = f.read()
     f.close()
     print s
     tree = et.fromstring(s)
     # get video
     el = tree.find("./Video/Media/Part")
     print el.attrib["key"]
     print "fullpath", fullpath
     # Construct the path to the media.
     o = urlparse(fullpath)
     mediapath = o.scheme + "://" + o.netloc + el.attrib["key"]
     print "mediapath", mediapath
     global omx
     omx = OMXPlayer(mediapath)
     omx.toggle_pause()
Ejemplo n.º 14
0
def playFile():
    global player
    global playerInfo
    global playerstatus

    print playerInfo

    if player:
        print "player already launched!"
        return
    print "launching OMXPlayer"
    player = OMXPlayer(playerInfo["file"], playerInfo["args"])
    # The player will initially be paused
    if playerInfo.has_key("mute") and playerInfo["mute"] == "True":
        print "we need to mute"
        player.toggle_mute()
    if playerInfo.has_key("vol"):
        print "setting volume to %d" % int(playerInfo["vol"])
        player.set_vol(int(playerInfo["vol"]))
    playerstatus = "queued"
    print "playFile exit"
Ejemplo n.º 15
0
def play_omx(request, link):
	global execucoes
	dados_post = json.loads(request.body)

	endereco_ip = dados_post['endereco_ip']
	usuario = dados_post['usuario']
	senha = dados_post['senha']

	omxplayer = None
	for execu in execucoes:
		if execu['token'] == request.COOKIES['csrftoken']:
			if execu['omxplayer'] == None:
				omxplayer = OMXPlayer(endereco_ip, link.execucao.ip_executando, link.execucao.porta_executando, usuario, not link.dublado, senha, link.legenda)		
				execu['omxplayer'] = omxplayer	
			else:				
				execu['omxplayer'].reininiciar(link.execucao.ip_executando, link.execucao.porta_executando, not link.dublado, link.legenda)
Ejemplo n.º 16
0
    def PlayMedia(self, fullpath, tag, unknown1, unknown2, unknown3):
        global parsed_path
        global media_key
        global duration
        
        parsed_path = urlparse(fullpath)
        media_path = parsed_path.scheme + "://" + parsed_path.netloc + tag

        self.media = self.plex.getMedia(media_path)
        
        #print 'mediapath', mediapath
        if(self.omx):
            self.Stop()
        transcodeURL = self.media.getTranscodeURL()
        print transcodeURL
        self.omx = OMXPlayer(transcodeURL, args=self.omxArgs, start_playback=True)
Ejemplo n.º 17
0
    def PlayMedia(self, fullpath, startPosition):  # , tag, unknown1, unknown2, unknown3):
        global parsed_path
        global media_key
        global duration

        # print startPosition
        # 		print 'Args'
        # 		print self.omxArgs

        # not supported in HLS video stream
        # 		if (startPosition != 0):
        # 			self.omxArgs += " -f " + str(startPosition)
        # 			print self.omxArgs

        if self.omx:
            self.Stop()
        print fullpath
        self.omx = OMXPlayer(fullpath, args=self.omxArgs, start_playback=True)
Ejemplo n.º 18
0
 def run(self):
     omx = OMXPlayer(self.path, args=self.args)
     self.player_queue.put(omx)
     omx.toggle_pause()
     last_position = 0
     wait_time = 10
     while True:
         time.sleep(1)
         if not omx.is_running():
             self.player_queue.get()
             self.player_queue.task_done()
             break
         elif not omx.paused and omx.position == last_position:
             wait_time = wait_time - 1
             if wait_time <= 0:
                 omx.stop()
         else:
             last_position = omx.position
Ejemplo n.º 19
0
Archivo: tv.py Proyecto: emi420/undertv
    def positionChecker(self):
        if not settings['CONTINUOUS_PLAYBACK']:            
            while True:
                if self.video:
                    if self.video.finished:
                        self.video = None
                    if self.waitingvideo and not self.waitingvideo.paused:
                        self.waitingvideo.stop()
                        self.waitingvideo = None

                else:
                   if not self.waitingvideo:
                        self.waitingvideo = OMXPlayer(settings['VIDEO_WAITING_PATH'], '-o hdmi -b --loop', start_playback=True) 

                sleep(0.5)
        else:

            while True:
                if self.video and self.video.finished:
                    self.video = None
                    self.random()
                sleep(0.5)
Ejemplo n.º 20
0
def video(request):
    global omx
    global stapwd, setpwd, softPath

    po = yield from request.post()
    if 1:  #po['p'] == stapwd:
        if po['m'] == 'play':
            #print('video play...')
            omx = OMXPlayer(softPath + 'Videos/' + po['d'] + '.mp4',
                            softPath + po['i'])
            tbody = '{"a":"video","b":"play"}'

        elif po['m'] == 'stop':
            omx.stop()
            tbody = '{"a":"video","b":"stop"}'

        elif po['m'] == 'pause':
            omx.toggle_pause()
            tbody = '{"a":"video","b":"pause"}'
    else:
        tbody = '{"p":"error"}'

    print(tbody)
    return web.Response(headers='', body=tbody.encode('utf-8'))
Ejemplo n.º 21
0
    def __init__(self, num):
        self.integer = num

    def make_playlist(path):
        temp = os.listdir(path)
        for name in temp:
            name2 = name.replace(" ", "")
            os.system("mv " + name + ".mp3 " + name2 + ".mp3 -i")
        temp2 = os.listdir(path)
        shuffle(temp2)
        return temp2


try:
    GPIO.add_event_detect(playpausePin, GPIO.RISING)
    player = OMXPlayer('/home/pi/Desktop/Music/' + temp2[i])
    player.toggle_pause()
    about_to_toggle_pause = False
    x = dumb(0)

    def play_pause(pin_num):
        y = x
        if y.integer == 0:
            y.integer = 1
            player.toggle_pause()

    def skip(pin_num):
        i = i + 1
        player = OMXPlayer('/home/pi/Desktop/Music/' + temp2[i])

    GPIO.add_event_callback(playpausePin, play_pause)
Ejemplo n.º 22
0
 def singleVideoLoop(self, filename):
     duration = self.getVideoDurationSeconds(filename)
     fullPath = self.mediaPath + filename
     print "VIDEO PATH: ", fullPath
     looper1 = OMXPlayer(fullPath, start_playback=True)
     looper2 = OMXPlayer(fullPath, start_playback=True)
     looper2.toggle_pause()
     looper1Active = True
     pos = 0
     while self.config['repeat'] and playerState == PLAYER_STARTED:
         if looper1Active:
             pos = looper1.position
         else:
             pos = looper2.position
         # print "Position: ", pos
         if pos > duration -2:
             print "TOGGLING LOOPERS..."
             # start other looper, wait 3 seconds and reload current looper for next round
             if looper1Active:
                 looper2.toggle_pause()
                 looper1.stop()
                 time.sleep(1)
                 looper1 = OMXPlayer(fullPath, start_playback=True)
                 looper1.toggle_pause()
             else:
                 looper1.toggle_pause()
                 looper2.stop()
                 time.sleep(1)
                 looper2 = OMXPlayer(fullPath, start_playback=True)
                 looper2.toggle_pause()
             looper1Active = not looper1Active
         time.sleep(0.1)
     if looper1:
         looper1.stop()
     if looper2:
         looper2.stop()
Ejemplo n.º 23
0
with error_handler.applicationbound():

    Config = ConfigParser.ConfigParser()
    Config.read('/etc/videodoor/videodoor.ini')
    SensorPin = Config.getint('hardware','SensorPin')
    log.debug('setting up GPIO pin %i...' % SensorPin)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(SensorPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    log.debug('done.')

    log.debug('Setting up the omxplayer instance...')
    File = Config.get('video','File')
    Options = Config.get('video','Options')
    omx_status = False
    log.info('initializing videoplayer with file %s and options %s' % (File, Options))
    omx = OMXPlayer(File, Options)
    log.debug('done.')

    def start_video():
        global omx, omx_status
        if(omx_status):
    	    log.warn('video already running')
        else:
        	omx.toggle_pause()
        	omx_status = True
        	log.info('door opened')

    def stop_video():
        global omx, omx_status
        if(omx_status):
        	omx.toggle_pause()
Ejemplo n.º 24
0
class Player:
    def __init__(self, video):
        self.video = video
        screenWidth, screenHeight = getScreenSize()
        if sys.platform == 'darwin':
            self.player = MPlayerX(self.video, screenWidth, screenHeight)
        else:
            self.player = OMXPlayer(self.video, screenWidth, screenHeight)
        self.from_position = video.progress

    def getUrls(self):
        if self.video.realUrl == playlistStorage:
            with open(playlistStorage, 'r') as f:
                urls = [v.strip() for v in f.readlines() if v.startswith('http')]
        else:
            urls = [self.video.realUrl]
        delta = 0
        if int(self.video.progress) > 30:
            if len(self.video.sections) <= 1:
                urls = urls
                delta = int(self.video.progress)
            else:
                new_progress, c_idx = self.video.getSectionsFrom(self.video.progress)
                urls = urls[c_idx:]
                delta = int(self.video.progress - new_progress)
        logging.info("urls = %s, delta = %s", urls, delta)
        return (urls, delta)

    def getFfmpegCmd(self, ss, inputFile, outputFile):
        if ss > 30:
            return 'nice -n 19 ffmpeg -ss %s -i "%s" -ss %s -c copy -bsf:v h264_mp4toannexb -y -f mpegts %s 2>%s.log' \
                   % (ss - 30, inputFile, 30, outputFile, outputFile)
        else:
            return 'nice -n 19 ffmpeg -i "%s" -c copy -bsf:v h264_mp4toannexb -y -f mpegts %s 2>%s.log' \
                   % (inputFile, outputFile, outputFile)

    def init(self):
        # Check the progress and decide the download cmd
        self.video.playUrl = "/tmp/all.ts"
        if len(self.video.sections) <= 1:
            # Unsplitted file
            if self.video.progress <= 30:
                urls, delta = self.getUrls()
                self.video.downloader = MultiDownloader(urls, alternativeUrls=self.video.alternativeUrls)
                self.video.downloader.getSizeInfo()
                self.video.download_args = '%s > %s 2>/tmp/cat.log' % (self.video.downloader.getCatCmds()[0], self.video.playUrl)
            else:
                self.video.downloader = None
                self.video.download_args = self.getFfmpegCmd(self.video.progress, self.getUrls()[0][0], self.video.playUrl)
        else:
            # Splitted file
            urls, delta = self.getUrls()
            self.video.downloader = MultiDownloader(urls, alternativeUrls=self.video.alternativeUrls)
            self.video.downloader.getSizeInfo()
            catCmds = self.video.downloader.getCatCmds()
            ffmpeg_part = "/tmp/ffmpeg_part"
            p_list = []
            download_lines = []
            for idx, catCmd in enumerate(catCmds):
                pname = os.path.join(ffmpeg_part, str(idx))
                newFifo(pname)
                if idx == 0 and delta > 30:
                    download_lines.append("{\n%s | %s\n}" % (catCmd, self.getFfmpegCmd(delta, "-", pname)))
                else:
                    download_lines.append("{\n%s | %s\n}" % (catCmd, self.getFfmpegCmd(0, "-", pname)))
                p_list.append(pname)
            ffmpeg_input = " ".join(p_list)
            download_args = 'cat %s | ffmpeg -f mpegts -i - -c copy -y -f mpegts %s 2> /tmp/merge.log &\n' \
                             % (ffmpeg_input, self.video.playUrl)
            download_args += " && ".join(download_lines)
            self.video.download_args = download_args

    def download(self, lock):
        if self.video.downloader:
            self.video.downloader.setLock(lock)
            self.video.downloader.start()

    def play(self, lock):
        # New a thread to play
        self.playThread = Thread(target=self.play_thread, args=(lock,))
        self.playThread.daemon = True
        self.playThread.start()

    def play_thread(self, lock):
        with lock:
            logging.info("Got lock and play now")
            self.player.play()
            interval = 0
            while self.player.isalive():
                time.sleep(1)
                interval += 1
                self.video.progress = self.from_position + self.getPosition()
                if not imgService.stop and self.video.progress > 0:
                    imgService.end()
                if interval % 10 == 0:
                    db_writeHistory(self.video)
            if imgService.stop:
                imgService.begin(FINISHED)

    def stop(self):
        logging.info("Stop downloader")
        if self.video.downloader:
            self.video.downloader.stop()
        logging.info("Stop player")
        self.player.stop()

    def getPosition(self):
        return int(self.player.position / 1000000)

    def isAlive(self):
        return self.player.isalive()

    def toggle_pause(self):
        self.player.toggle_pause()

    def volup(self):
        self.player.volup()

    def voldown(self):
        self.player.voldown()
Ejemplo n.º 25
0
import pygame
import time
from  pyomxplayer import OMXPlayer

pygame.init()
pygame.mouse.set_visible(False)

screen=pygame.display.set_mode((0,0),pygame.FULLSCREEN)

screen.fill((0,0,0))

done = False

player = OMXPlayer('videos/stag.mp4', '-o local')
player.toggle_pause() 

while not done:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			done = True
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_ESCAPE:
				done = True
	time.sleep(0.01)

pygame.quit()

Ejemplo n.º 26
0
def main():

	global Team1Option
	global Team2Option
	global firstteam
	global Team1_Score
	global Team2_Score
	global screen
	global movie
	
	Team1_Score = 0
	Team2_Score = 0	
	Team_color= ("Ambos","Azul","Rojo")
	_Rojo = (255,0,0)
	_Azul = (0,0,255)
	
	#Configure interrupt handlers for inputs 0 to 5 
	#which are connected to the teams push buttons options
	#Team 1 : Azul
	listener.register(0,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 1 - Option A
	listener.register(1,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 1 - Option B
	listener.register(2,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 1 - Option C
	#Team 2 : Rojo
	listener.register(3,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 2 - Option A
	listener.register(4,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 2 - Option B
	listener.register(5,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 2 - Option C
	
	#Activate the interrupt handler
	listener.activate()
	
	#Create an array of flags. Each element indicates if that question was already asked or not,
	#to avoid repeating the same question during a game session
	question_executed = [0] * len(Question_Answer)
	
	#Clear console screen
	os.system('clear')
	
	init_screen()

	#TODO: Play video: "invitacion_a_jugar"
	#TODO: Wait of any of the Teams to press a key
	
	##########
	printxy(2,0,"Play video: Invitacion a Jugar!")
	omx = OMXPlayer("media/Trivia_Video0.mp4")
	movie = pygame.movie.Movie('media/Trivia_Video6.mpg')
	screen = pygame.display.set_mode((1920,1080))#movie.get_size())#,pygame.FULLSCREEN)
	movie_screen = pygame.Surface(movie.get_size()).convert()
	movie.set_display(movie_screen)
#	movie.play()
#	playing = True
#	while playing:
#		for event in pygame.event.get():
#			if event.type == pygame.QUIT:
#				movie.stop()
#				playing = False
#
#		screen.blit(movie_screen,(0,0))
#		pygame.display.update()
#		clock.tick(FPS)

#	pygame.quit()
	#movie = pygame.movie.Movie('media/hst_1.mpg')
#	movie.play()
	
#	while movie.get_busy():
#		for event in pygame.event.get():
#			if event.type == pygame.KEYDOWN:
#				movie.stop()				
#		pygame.quit()
	
	
	init_vars()
	firstteam=Wait_for_Key(2,1,"Waiting for a Team to accept playing !   ")
#	movie.stop()
	omx.stop()
	
	#TODO: Detect which team pressed a key 
	if firstteam==1:
		#play video: invitacion_a_jugar_rojo
		wait_for_team=2
		omx = OMXPlayer("media/Trivia_Video1.mp4")
	else:
		#play video: invitacion_a_jugar_Azul
		wait_for_team=1
		omx = OMXPlayer("media/Trivia_Video2.mp4")
	printxy (2,3,"Team %s is on!" %(Team_color[firstteam]))
	
	init_vars()
	firstteam=0

##########
	#movie = pygame.movie.Movie('media/Trivia_Video0.mpg')
	#movie = pygame.movie.Movie('media/hst_1.mpg')
	#movie.play()
	
	while firstteam<>wait_for_team:
		init_vars()
		#TODO: Play invitacion_a_jugar_rojo o invitacion_a_jugar_Azul depending on who already pressed a button
		firstteam=Wait_for_Key(2,5,"Waiting for Team %s to accept!         " % (Team_color[wait_for_team]))
		
	#movie.stop()
	omx.stop()
	
#	while firstteam<>wait_for_team:
#		init_vars()
#		#TODO: Play invitacion_a_jugar_rojo o invitacion_a_jugar_Azul depending on who already pressed a button
#		firstteam=Wait_for_Key(2,5,"Waiting for Team %s to accept!         " % (Team_color[wait_for_team]))
		
					
		
	printxy (2,8,"Team %s accepted the challenge!" % (Team_color[wait_for_team]))
	omx = OMXPlayer("media/Trivia_Video3.mp4")
	printxy (2,10,"Play video - Explicar Juego!")
	sleep(5)
	
	#TODO: Play video: explicar_juego
	
	#Ask 3 questions
	for x in range(1, 4):
		
		init_vars()
		timeout_tmr=0
		sandclockindex=0
		
		current_question = choose_question(Question_Answer,question_executed)

		# initialize round scores
		Team1_Round_Score = 0
		Team2_Round_Score = 0
		
		background = pygame.image.load('media/'+screen_dict['pregunta_%d' % (x)]).convert_alpha()
		background = pygame.transform.scale(background , (1920,1080))
	
		font = pygame.font.SysFont("renegademaster", 150, bold = 0)
		
		
		while Team1Option==0 or Team2Option==0:
			update_scr(x,current_question+1,timeout_tmr, sandclockindex)
			timeout_tmr+=1
		
			pf.output_pins[7].toggle()
		
			sleep(1)
			sandclockindex+=1
			if sandclockindex>=len(sandclock2):
				sandclockindex=0
		
			if timeout_tmr>30:
				if Team1Option==0:
					Team1Option=99
				if Team2Option==0:
					Team2Option=99
		
			count_down = font.render("{:02d}".format(timeout_tmr),True, (255,255,0)) 
			count_down_pos = count_down.get_rect()
			count_down_pos.centerx = background.get_rect().centerx
			count_down_pos.centery = 900

			screen.blit(background, (0, 0))
			screen.blit(count_down, count_down_pos)
			pygame.display.update()
			
			update_scr(x,current_question+1,timeout_tmr, sandclockindex)
		
		# Calculate the scores for Team1
		if Team1Option == Question_Answer[current_question]:
			Team1_Round_Score = 10
			if firstteam == 1:
				Team1_Round_Score += 5

		# Calculate the scores for Team2
		if Team2Option == Question_Answer[current_question]:
			Team2_Round_Score = 10
			if firstteam == 2:
				Team2_Round_Score += 5

		# Set the winner
		if Team1_Round_Score > Team2_Round_Score:
			Round_Winner = 1
		elif Team1_Round_Score < Team2_Round_Score:
			Round_Winner = 2
		else:
			Round_Winner = 0

		# Accumulate the total scores
		Team1_Score += Team1_Round_Score
		Team2_Score += Team2_Round_Score

		# Present the correct answer
		printxy(2,10,'Pregunta #%d  Code %d - correct Answer: %d' % (
		x, current_question + 1, Question_Answer[current_question]))

		# Present who was the winner
		if Round_Winner > 0:
			printxy(2,12,"Playing: Video %d: Equipo %d wins this round" % (Round_Winner+6,Round_Winner))
		else:
			if Team1Option==99 and Team2Option==99:
				printxy(2,12,"Playing: Video x: Time Out! nadie respondio")
			else:
				printxy(2,12,"Playing: Video 6: Respondieron ambos incorrectamente")

		
		#printxy(2,12,"Question #%d  Question Code %d - correct Answer: %d" % (x, current_question + 1, Question_Answer[current_question]))
		printxy(2,14,"Team 1 Score=%d" % (Team1_Score))
		printxy(2,15,"Team 2 Score=%d" % (Team2_Score))

		printxy(2,18,"Play video: Explicacion pregunta %d" % (current_question+1))
		omx = OMXPlayer("media/Trivia_Video%d.mp4" % (x+6))
		sleep(10)

	os.system('clear')
	printxy(2,2,"=============================================================")
	if Team1_Score>Team2_Score:
		printxy(2,4,'TEAM 1 is the Winner!!! with %d over %d' % (Team1_Score, Team2_Score))
	elif Team1_Score<Team2_Score:
		printxy(2,4,"TEAM 2 is the Winner!!! with %d over %d" % (Team2_Score, Team1_Score))
	else:
		printxy(2,4,"Tie : both team with Team 1=%d and Team 2=%d" % (Team1_Score, Team2_Score))
	printxy(2,6,"=============================================================")

	printxy(2,8,Question_Answer)
	printxy(2,9,question_executed)
	stop()
            if zoom <= 0:
                zoom = 1
            print str(1-zoom) + ":" + str(zoom)
            camera.zoom = (.5 * (1-zoom), 0, zoom, zoom)
        else:
            calibrate_colors()
       
    lost_one = False
    for k, v in last_seen.iteritems():
        now = time.time() - start_time
        if now - v > lost_item_delay:
            print k + " has gone missing " + str(now - v) + " seconds"
            if vids[k]:
                if omx:
                    omx.stop()
                omx = OMXPlayer(vid_path + "/" + vids[k], start_playback=True)
                curr_vid_color = k
            lost_one = True
        else:
            if k == curr_vid_color and omx:
                omx.stop()
    if lost_one:
        last_seen = {}

if omx:
    omx.stop()

print "\nhsv_ranges ="
pp.pprint(hsv_ranges)
print "\nrects ="
pp.pprint(rects)
Ejemplo n.º 28
0
import os
from pyomxplayer import OMXPlayer

loop1= OMXPlayer('/home/pi/videos/background.mp4', '-o local', start_playback=True)
loop2 = OMXPlayer('/home/pi/videos/Nature.mp4', '-o local', start_playback=True)
loop2.toggle_pause()

position = loop1.position/1000000
if position > 12.8:
    loop1.toggle_pause()

sleep(2)
os.system('pkill -9 -f "/usr/bin/omxplayer.bin -s /home/pi/videos/background.mp4 -o local"')
os.system('pkill -9 -f "/bin/bash /usr/bin/omxplayer -s /home/pi/videos/background.mp4 -o local"')
sleep(2)
loop1= OMXPlayer('/home/pi/videos/background.mp4', '-o local', start_playback=True)
loop1.toggle_pause()
Ejemplo n.º 29
0
        print (starttime - est.localize(datetime.now())).seconds
        logger.info("It is currently {}".format(str(datetime.now())))
        logger.info("Waiting until {}".format(str(starttime)))
        while(est.localize(datetime.now()) < starttime):
            time.sleep(.1)
        logger.info("Done waiting")
    except Exception, e:
        print "exception"
        print Exception
        print e
        logger.debug("Improperly formatted starttime: was it ISO?")
    return

#load movie and start paused
try:
    o = OMXPlayer(sys.argv[1])  # carpenter1.mov 'carp/carp/carpenter1_ge.mov'
except Exception, e:
    logger.error('Failed to open movie?', exc_info=True)

logger.info("OMXPlayer is: {}".format(str(o)))
o.pause()

#check to see if there's a starttime, in iso format, in which case wait
if len(sys.argv) >= 3:
    wait_for_starttime(sys.argv[2])

os.system('killall cat;clear')
o.play()
logger.info("Playing")
time.sleep(DELAY_AFTER_PRESSING_START)  # helps prevent instant stopping if computer hangs on start of play
Ejemplo n.º 30
0
	time.sleep(.1)
wii.led = 0
time.sleep(1)

for i in [1, 2, 4, 8, 4, 2, 1, 2, 4, 8, 4, 2, 1, 2, 4, 8, 4, 2, 1, 0]:
	wii.led = i
	time.sleep(.1)
wii.led = 6
wii.rpt_mode = cwiid.RPT_BTN

ambients = ["atmosphere.wav", "lair.wav"]
music = ["darkmark.wav","voldemort.wav","maze.wav"]
folly = ['sadtrumbone.wav', 'thunder.wav']

mixer.init()
player = OMXPlayer('videos/stag.mp4', '-o local')

used_sec = 0


done=False

while not done:
	if mode == "ambient":
		if not mixer.music.get_busy():
			play_wav('effects/'+random.choice(ambients));
	if mode == "music":
		if not mixer.music.get_busy():
			play_wav('effects/'+random.choice(music));
	sec = time.localtime(time.time()).tm_sec
	if(sec % validation_sec == 0 and sec != used_sec):
 def test_opening_mp4_file(self):
     player = OMXPlayer('./tests/test.mp4')
     player.toggle_pause()
     time.sleep(1)
     player.stop()
     self.assertTrue("Did not complete playing example without errors")
Ejemplo n.º 32
0
class AirPlay:

    playing = False
    seekable = False
    action_play = False
    action_play_pause = False
    add_to_playlist_and_play = ""
    action_stop = False
    action_seek_time = 0
    omxArgs = ""

    def __init__(self):
        args = len(sys.argv)
        if args > 1:
            if sys.argv[1] == "jack":
                self.omxArgs = ""
                print "Audio output over 3,5mm jack"
        else:
            self.omxArgs = "-o hdmi"
            print "Audio output over HDMI"

        self.videoAirPlay = None
        self.videoAirPlay = self
        self.omx = None

        self.videoAirPlay.service = VideoAirPlayPlayer(
            videoAirPlay=self.videoAirPlay,
            name="VideoAirPi on %s" % (platform.node()),
            host=self.get_ip_address("eth0"),
            port=8000,
        )

    def signal_handler(self, signal, frame):
        print "\nQuiting - please wait...."
        self.Stop()
        self.videoAirPlay.service.exit()
        sys.exit(0)

    def get_ip_address(self, ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack("256s", ifname[:15]))[20:24])  # SIOCGIFADDR

    def PlayMedia(self, fullpath, startPosition):  # , tag, unknown1, unknown2, unknown3):
        global parsed_path
        global media_key
        global duration

        # print startPosition
        # 		print 'Args'
        # 		print self.omxArgs

        # not supported in HLS video stream
        # 		if (startPosition != 0):
        # 			self.omxArgs += " -f " + str(startPosition)
        # 			print self.omxArgs

        if self.omx:
            self.Stop()
        print fullpath
        self.omx = OMXPlayer(fullpath, args=self.omxArgs, start_playback=True)

    def Pause(self, message):
        if self.omx:
            self.omx.set_speed(1)
            self.omx.toggle_pause()

    def Play(self, message):
        if self.omx:
            ret = self.omx.set_speed(1)
            if ret == 0:
                self.omx.toggle_pause()

    def Stop(self, message=""):
        if self.omx:
            self.omx.stop()
            self.omx = None

    def do_activate(self):
        pass

    def do_deactivate(self):
        self.videoAirPlay.service.__del__()

    def is_playing(self):
        return self.playing

    def get_property(self, propertyType):
        return 100

    def action_stop(self):
        pass

    def action_play(self):
        pass

    def is_seekable(self):
        return self.seekable
Ejemplo n.º 33
0
 def singleVideoLoop(self, filename):
     duration = self.getVideoDurationSeconds(filename)
     fullPath = self.mediaPath + filename
     #print "VIDEO PATH: ", fullPath
     looper1 = OMXPlayer(fullPath, start_playback=True)
     looper2 = OMXPlayer(fullPath, start_playback=True)
     looper2.toggle_pause()
     looper1Active = True
     pos = 0
     while self.config['repeat'] and playerState == PLAYER_STARTED:
         if looper1Active:
             pos = looper1.position
         else:
             pos = looper2.position
         # print "Position: ", pos
         if pos > duration - 2:
             #print "TOGGLING LOOPERS..."
             # start other looper, wait 3 seconds and reload current looper for next round
             if looper1Active:
                 looper2.toggle_pause()
                 looper1.stop()
                 time.sleep(1)
                 looper1 = OMXPlayer(fullPath, start_playback=True)
                 looper1.toggle_pause()
             else:
                 looper1.toggle_pause()
                 looper2.stop()
                 time.sleep(1)
                 looper2 = OMXPlayer(fullPath, start_playback=True)
                 looper2.toggle_pause()
             looper1Active = not looper1Active
         time.sleep(0.1)
     if looper1:
         looper1.stop()
     if looper2:
         looper2.stop()
Ejemplo n.º 34
0
    def playStep(self):
        # single step can contain multiple movies
        try:
            pdb.set_trace()
        except:
            pass
        curStepFirstPlayer = None
        curStepSecondPlayer = None
        step = ""
        layNum = 0
        while True:
            self.lock.acquire()
            # print "CURRENT STEP: %s" % self.currentStep
            if self.currentStep == "<STOP>":
                step = ""
                self.lock.release()
                sleep(0.01)
                continue

            if (not self.currentStep):
                self.lock.release()
                sleep(0.01)
                continue
            elif step == self.currentStep:
                self.lock.release()
                sleep(0.01)
                continue

            step = self.currentStep

            self.lock.release()

            # playing step
            currentStepNeedStop = False
            curStepFirstPlayer = None
            curStepSecondPlayer = None

            filesInStep = len(self.cfg['steps'][step])
            for idx, curFile in enumerate(self.cfg['steps'][step]):
                if currentStepNeedStop:
                    break

                movieId = curFile['movie']
                curFileLen = -1
                if 'length' in curFile:
                    curFileLen = curFile['length']

                isLoop = False
                if 'loop' in curFile:
                    isLoop = curFile['loop']

                needFlash = False
                if 'flash' in curFile:
                    needFlash = curFile['flash']

                movieFile = self.getMoviePathByMovieId(movieId)
                srtFile = self.getSRTPathByMovieId(movieId)

                if idx == 0 and self.nextStepPlayer:
                    if step == self.stepIdForNextStepPlayer:
                        curStepFirstPlayer = self.nextStepPlayer
                    else:
                        # next steps is different from what we planning (not next - something another, may be previous)
                        self.nextStepPlayer.stop()

                    self.nextStepPlayer = None
                    self.stepIdForNextStepPlayer = ""
                elif curStepSecondPlayer:
                    curStepFirstPlayer = curStepSecondPlayer
                    curStepSecondPlayer = None

                if not curStepFirstPlayer:
                    # layNum += 1
                    curStepFirstPlayer = OMXPlayer(
                        movieFile,
                        #args='-o hdmi -p' + ("" if not isLoop else ' --loop'),
                        args='-o ' + audio_output + ' -p --layer '+str(layNum) + ((' --subtitles ' + srtFile + subtitles_font_arg) if srtFile else ''),
                        start_playback=not self.isFirstVideoMovie
                    )
                    curStepFirstPlayer.set_volume(1)

                self.needFlash = needFlash

                self.lock.acquire()
                self.currentPlayer = curStepFirstPlayer
                self.lock.release()

                # if self.isFirstVideoMovie:
                #     self.isFirstVideoMovie = False

                # nextFilePrepared = False
                # prepare the next video file with own omxplayer for smallest
                # gap between them
                # sleep(0.4)
                nextFileInStep = None
                # needPauseForInitNextPlayer = False
                if idx < filesInStep-1:
                    nextFileInStep = self.cfg['steps'][step][idx+1]
                    nextMovieFile = self.getMoviePathByMovieId(nextFileInStep['movie'])
                    nextSrtFile = self.getSRTPathByMovieId(nextFileInStep['movie'])
                    if nextFileInStep:
                        sleep(1)
                        layNum += 1
                        curStepSecondPlayer = OMXPlayer(
                            nextMovieFile,
                            #args='-o hdmi' + ("" if not nextFileInStep['loop'] else ' --loop'),
                            args='-o ' + audio_output + ' -p --layer ' + str(layNum) + ((' --subtitles ' + nextSrtFile + subtitles_font_arg) if nextSrtFile else ''),
                            start_playback=False,
                            hidemode=False
                        )

                        # pause for audio up
                        # self.togglePause()
                        # sleep(0.06)
                        # self.togglePause()

                        #self.currentPlayer.increase_volume()
                        #sleep(0.07)
                        #self.currentPlayer.decrease_volume()

                        #curStepSecondPlayer.set_volume(0)
                        #layNum += 1
                        # needPauseForInitNextPlayer = True

                    print 'Next file in step PREPARED'
                elif idx == (filesInStep-1):
                    # prepare first movie in next step
                    nextStep = self.getNextStepId(step)
                    if nextStep:
                        nextFileInStep = self.cfg['steps'][nextStep][0]
                        nextMovieFile = self.getMoviePathByMovieId(nextFileInStep['movie'])
                        nextSrtFile = self.getSRTPathByMovieId(nextFileInStep['movie'])

                        if nextFileInStep:
                            sleep(1)
                            # self.nextStepPlayer = OMXPlayer(
                            layNum += 1
                            self.nextStepPlayer = OMXPlayer(
                                nextMovieFile,
                                #args='-o hdmi' + ("" if not nextFileInStep['loop'] else ' --loop'),
                                args='-o ' + audio_output + ' -p --layer '+str(layNum) + ((' --subtitles ' + nextSrtFile + subtitles_font_arg) if nextSrtFile else ''),
                                start_playback=False,
                                hidemode=False
                            )

                            # self.togglePause()
                            # sleep(0.06)
                            # self.togglePause()

                            #self.currentPlayer.increase_volume()
                            #sleep(0.07)
                            #self.currentPlayer.decrease_volume()

                            #self.nextStepPlayer.set_volume(0)
                            #layNum += 1
                            self.stepIdForNextStepPlayer = nextStep
                            # needPauseForInitNextPlayer = True

                        print 'First file in next step PREPARED'

                    # while self.currentPlayer and not self.currentPlayer.finished:
                # if needPauseForInitNextPlayer:
                #     sleep(0.1)

                isRewinding = False
                while True:
                    # check current step may was changed
                    self.lock.acquire()
                    # print "self.currentStep != step: %s" % (self.currentStep != step)
                    if self.currentStep != step:
                        currentStepNeedStop = True
                        if curStepSecondPlayer:
                            curStepSecondPlayer.stop()
                            curStepSecondPlayer = None
                            # layNum -= 1

                        self.lock.release()
                        break
                    else:
                        if curFileLen > 0 and self.currentPlayer.position >= curFileLen and not isRewinding:
                            if (isLoop):
                                self.currentPlayer.rewind()
                                isRewinding = True
                                print 'SEEK playing by manual'
                                # sleep(0.2)
                            else:
                                self.lock.release()
                                print 'STOP playing by manual'
                                # layNum -= 1
                                break
                        elif self.currentPlayer and self.currentPlayer.finished:
                            self.lock.release()
                            # layNum -= 1
                            break

                        if self.currentPlayer.position < curFileLen:
                            # just rewinded
                            isRewinding = False

                    self.lock.release()
Ejemplo n.º 35
0
from gpiozero import LED, Button
import time
import sys

# we'll use a button to advance the slide show
yButton = Button(6,  pull_up=False, bounce_time=0.05)
# and an LED to make sure the button is working properly
yLed = LED(20)
yButton.when_pressed = yLed.on
yButton.when_released = yLed.off

# we'll use another button for quitting the program (since it runs fullscreen)
rButton = Button(19,  pull_up=False, bounce_time=0.05)

# sets up the video player
omx = OMXPlayer('../movs/MechanicalPrinciples.mov')

try:
    # run this next section forever, until user stops the programme by pressing button
    while True:
        # play video if button is pressed and video player is currently paused
        if yButton.is_pressed and omx.paused:
            omx.toggle_pause()
        # pause video if button is not pressed and player is not paused
        if (not yButton.is_pressed) and (not omx.paused):
            omx.toggle_pause()

        # when quit button is pressed, stop player and quit programme
        if rButton.is_pressed:
            omx.stop()
            sys.exit(0)
Ejemplo n.º 36
0
		

	# play a MP3 or MIDI music file using module pygame
	def checkfiletype(self,fn):
		ext = os.path.splitext(fn)[-1].lower()
		# Now we can simply use == to check for equality, no need for wildcards.
		if ext == ".mp3":
			self #haha
		elif ext == ".mp4":
			self #ha
		else:
			return False
		return True




if __name__ == "__main__":

	manager= channelManager(channel= "RCXOVNLNVK56GBQK2OCWR3GLY2DENRZG4")
	manager.readAll()
	shuffle(manager.filelist)
	for f in manager.filelist:
		print f
		omx = OMXPlayer(f)
		while omx.is_running():
			pass
			

       
Ejemplo n.º 37
0
class xbmcCommands:
    def __init__(self, omxArgs):
        self.media = None
        self.plex = PlexInterface()
        self.omx = None
        self.omxArgs = omxArgs

    def PlayMedia(self, fullpath, tag, unknown1, unknown2, unknown3):
        global parsed_path
        global media_key
        global duration
        
        parsed_path = urlparse(fullpath)
        media_path = parsed_path.scheme + "://" + parsed_path.netloc + tag

        self.media = self.plex.getMedia(media_path)
        
        #print 'mediapath', mediapath
        if(self.omx):
            self.Stop()
        transcodeURL = self.media.getTranscodeURL()
        print transcodeURL
        self.omx = OMXPlayer(transcodeURL, args=self.omxArgs, start_playback=True)

    def Pause(self, message):
        if(self.omx):
            self.omx.set_speed(1)
            self.omx.toggle_pause()

    def Play(self, message):
        if(self.omx):
            ret = self.omx.set_speed(1)
            if(ret == 0):
                self.omx.toggle_pause()

    def Stop(self, message=""):
        if(self.omx):
            self.omx.stop()
            self.omx = None

    def stopPyplex(self, message):
        self.Stop()
        global service
        pygame.quit()
        exit()

    def SkipNext(self, message = None):
        if(self.omx):
            self.omx.increase_speed()

    def SkipPrevious(self, message = None):
        if(self.omx):
            self.omx.decrease_speed()

    def StepForward(self, message = None):
        if(self.omx):
            self.omx.increase_speed()

    def StepBack(self, message = None):
        if(self.omx):
            self.omx.decrease_speed()

    def BigStepForward(self, message = None):
        if(self.omx):
            self.omx.jump_fwd_600()

    def BigStepBack(self, message = None):
        if(self.omx):
            self.omx.jump_rev_600()

    def getMilliseconds(self,s):
        hours, minutes, seconds = (["0", "0"] + ("%s" % s).split(":"))[-3:]
        hours = int(hours)
        minutes = int(minutes)
        seconds = float(seconds)
        miliseconds = int(3600000 * hours + 60000 * minutes + 1000 * seconds)
        return miliseconds

    def getPosMilli(self):
        return self.getMilliseconds(self.omx.position)
    
    def setPlayed(self):
        self.media.setPlayed()

    def isFinished(self):
        if(self.omx):
            finished = self.omx.finished
        else:
            finished = True
        return finished
    
    def isRunning(self):
        if(self.omx):
            return True
        return False

    def updatePosition(self):
        if self.isFinished():
            if (self.getPosMilli() > (self.media.duration * .95)):
                self.setPlayed()
            self.Stop()
        else:
            self.media.updatePosition(self.getPosMilli())
Ejemplo n.º 38
0
# Create event handler and subscribe to event
def handleEvent(count):
    #print "received count", count
    if count < 0:
	# We've reached the end of the input
	print "Finished. Total frames: ", handleEvent.numFrames
	omx.toggle_pause()
	omx.stop()
    
    elif shouldAdvanceFrame(count):
    	omx.step()
	blah =1
	handleEvent.numFrames += 1
handleEvent.numFrames = 0


# Initialise video
omx = OMXPlayer('smaller.mp4', '--no-osd', start_playback=False)

# Get the video started, then wait a short while before beginning the mock thread
omx.step()
time.sleep(1)	

#subscribe to events
zope.event.subscribers.append(handleEvent)
print "subscribed"

#Start up the mock
thread = Thread(target=mock)
thread.start()
Ejemplo n.º 39
0
def main():

	global Team1Option
	global Team2Option
	global question_answer
	global firstteam
	global Team1_Score
	global Team2_Score
	global screen
	global movie
	global COUNTDOWN_POS_X
	global COUNTDOWN_POS_Y
	global COUNTDOWN_FONT
	global COUNTDOWN_FONT_SIZE
	global SCREEN_RESOLUTION
	
	team_color= ("Ambos","Azul","Rojo")

	current_question = -1       #Stores the question being asked
	
	turn_off_leds()
	
	#Configure interrupt handlers for inputs 0 to 5 
	#which are connected to the teams push buttons options
	#Team 1 : Azul
	listener.register(0,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 1 - Option A
	listener.register(1,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 1 - Option B
	listener.register(2,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 1 - Option C
	#Team 2 : Rojo
	listener.register(3,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 2 - Option A
	listener.register(4,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 2 - Option B
	listener.register(5,piface.IODIR_FALLING_EDGE, ButtonPressed)	# Team 2 - Option C
	
	#Activate the interrupt handler
	listener.activate()
	
	#Create an array of flags. Each element indicates if that question was already asked or not,
	#to avoid repeating the same question during a game session
	question_executed = [0] * len(question_answer)
	
	#Clear console screen
	os.system('clear')
	
	#######################################
	# STEP 1: Invite to Play             
	#######################################
	#Initialize Graphic Screen
	init_screen()

	#Play Inviting to Play video
	printxy(2,0,"Play video: Invitacion a Jugar!")
	omx = OMXPlayer(screen_dict['invitacion_a_jugar'])

	#Initialize Game variables
	init_vars()
	#Wait until one of the teams presses a button
	#firstteam=Wait_for_Key(2,1,"Waiting for a Team to accept playing !   ")
	Wait_for_Key(2,1,"Waiting for a Team to accept playing !   ")
	
	#Stop Inviting to Play video
	omx.stop()
	
	#send_msg("Simpsons")

	#########################################################
	# STEP 2: Wait for the Other Team confirmation to play             
	#########################################################
	
	if firstteam==1:
		#play video: invitacion_a_jugar_rojo
		wait_for_team=2
		omx = OMXPlayer(screen_dict['invitacion_a_jugar_rojo'])
	else:
		#play video: invitacion_a_jugar_Azul
		wait_for_team=1
		omx = OMXPlayer(screen_dict['invitacion_a_jugar_azul'])
	
	printxy (2,3,"Team %s is on!" %(team_color[firstteam]))
	
	init_vars()
	firstteam=0

	while firstteam<>wait_for_team:
		init_vars()
		#TODO: Play invitacion_a_jugar_rojo o invitacion_a_jugar_Azul depending on who already pressed a button
		#firstteam=
		Wait_for_Key(2,5,"Waiting for Team %s to accept! %s        " % (team_color[wait_for_team],screen_dict['invitacion_a_jugar_azul']))

	printxy (2,8,"Team %s accepted the challenge!"%team_color[wait_for_team])
	
	omx.stop()

	#########################################################
	# STEP 3: Explain how to play this game
	#########################################################

	printxy (2,10,"Play video - Explicar Juego!")
	omx = OMXPlayer(screen_dict['explicar_juego'])
	
	#TODO: delay necesita ser igual a duracion del video
	sleep(10)
	omx.stop()
	
	#########################################################
	# STEP 4: Go through the questions
	#########################################################
	Team1_Score = 0
	Team2_Score = 0	
	
	
	#Ask 3 questions
	for x in range(1, 4):
		
		init_vars()
		timeout_tmr=30
		sandclockindex=0
		turn_off_leds()
		
		###################################################################
		# STEP 5: Select a question randomly and present it on the screen
		###################################################################		
		
		#Select one question randomly
		current_question = choose_question(question_answer,question_executed)

		#initialize round scores
		Team1_Round_Score = 0
		Team2_Round_Score = 0
		
		#Render to a surface "background" the question selected
		background = pygame.image.load(screen_dict['pregunta_%d' % (current_question+1)]).convert_alpha()
		background = pygame.transform.scale(background , SCREEN_RESOLUTION)
		
		#Select the font used for the countdown timer
		font = pygame.font.SysFont(COUNTDOWN_FONT, COUNTDOWN_FONT_SIZE, bold = 0)
		
		#####################################################################
		# STEP 6: Wait for the answers of each team and start the countdown
		#####################################################################	

		pygame.mixer.music.load(COUNTDOWN_DING)
			
		
		#Wait until a team picks an option before the time runs out
		while Team1Option==0 or Team2Option==0:
			#update debug screen info
			update_scr(x,current_question+1,timeout_tmr, sandclockindex)
			
			#increase timeout timer in 1sec
			timeout_tmr-=1
		
			#Just make LED7 on Piface board toggle every second that passes to know that the system is alive!
			pf.output_pins[7].toggle()
		
			#Wait one second
			sleep(.586) #1-.314)

			#Tic sound
			pygame.mixer.music.play(1)
			
			#Sandclock: is just an animation on the debug screen to know that the system is waiting
			#increase the sandclock pointer to control the animation
			sandclockindex+=1
			
			#reset pointer to loop back the animation
			if sandclockindex>=len(sandclock2):
				sandclockindex=0
			
			#If Time is up flag the teams that have not answered
			if timeout_tmr<=0:
				if Team1Option==0:
					Team1Option=99	#Team1 didn't answer on time
				if Team2Option==0:
					Team2Option=99	#Team2 didn't answer on time
		
			#Render the surface "count_down" that holds the text
			count_down = font.render("{:02d}".format(timeout_tmr),True, (255,255,0)) 
			
			#get the text dimensions and calculate the final position of the text
			count_down_pos = count_down.get_rect()
			count_down_pos.centerx = COUNTDOWN_POS_X  #background.get_rect().centerx
			#TODO: create parameter
			count_down_pos.centery = COUNTDOWN_POS_Y  #900

			#Paste the background on the screen
			screen.blit(background, (0, 0))
			#Paste the text on the screen at the desired position
			screen.blit(count_down, count_down_pos)
			#Update the screen
			pygame.display.update()
			
		
			#update the debug screen
			update_scr(x,current_question+1,timeout_tmr, sandclockindex)
		
		
		######################################
		# STEP 7: Show the correct answer 
		######################################
		pygame.mixer.music.stop()
		
		#Clear the graphic screen
		screen.fill((0, 0, 0))	
		pygame.display.update()
		
		## Present the correct answer
		printxy(2,18,"Play video: Explicacion pregunta %d" % (current_question+1))
		omx = OMXPlayer(screen_dict['video_pregunta_%d' %(current_question+1)])

		printxy(2,10,'Pregunta #%d  Code %d - correct Answer: %d' % (
		x, current_question + 1, question_answer[current_question]))	
		
		#TODO: delay tiene que ser de la duracion del video de la pregunta
		sleep(10)
		omx.stop()
		
		Team1_Correct=False
		Team2_Correct=False
		
		# Who answered correctly?
		if Team1Option == question_answer[current_question]:
			Team1_Correct=True
		if Team2Option == question_answer[current_question]:
			Team2_Correct=True

		background_image = ""
		
		# Display the proper background	
		if   Team1_Correct and Team2_Correct:
			background_image = screen_dict['correcto_ambos']
		elif Team1_Correct and not Team2_Correct:
			background_image = screen_dict['correcto_azul']
		elif not Team1_Correct and Team2_Correct:
			background_image = screen_dict['correcto_rojo']
		else:
			background_image = screen_dict['incorrecto_ambos']
		
		#Render to a surface "background" the question selected
		background = pygame.image.load(background_image).convert_alpha()
		
		#Resize background to ensure it fills the screen
		background = pygame.transform.scale(background , SCREEN_RESOLUTION)
		
		#Select the font used for the scores
		font = pygame.font.SysFont("renegademaster", 150, bold = 0)
		
		##########################################################
		# STEP 8: Calculate the scores and display on the screen
		##########################################################
		pygame.mixer.music.load(SCORE_DING)
		
		if Team1_Correct or Team2_Correct:	

			#count up to 10
			for score_board_counter in range(1,11):
			
				#Is the Team 1 Answer correct?
				if Team1_Correct:	
					Team1_Score += 1

				#Is the Team 2 Answer correct?
				if Team2_Correct:
					Team2_Score += 1

				update_score(Team1_Score,Team2_Score,background)

				#TODO: PLAY bing!!! sound
				
				#sleep(.10)
				#Tic sound
				pygame.mixer.music.play(0)
				while pygame.mixer.music.get_busy():
					pygame.time.Clock().tick(5)
					
				#Wait 5sec before jumping to the next step
			sleep(5)
			
			###########################################################
			# STEP 9: Give more point to the Team that answered first
			###########################################################
			
			#Render to a surface "background" with the team who answered first
			background = pygame.image.load(screen_dict['respondio_primero_%s'%(team_color[firstteam].lower())]).convert_alpha()
			
			#Resize background to ensure it fills the screen
			background = pygame.transform.scale(background , SCREEN_RESOLUTION)
			
			#Select the font used for the scores
			font = pygame.font.SysFont("renegademaster", 150, bold = 0)
			
			skip_section=False
			
			#count up to 5
			for score_board_counter in range(1,6):
			
				#Was Team 1 the first to Answer correctly?
				if firstteam == 1:
					if Team1_Correct:	
						Team1_Score += 1
					else:
						skip_section=True
						break
				
				#Was Team 2 the first to Answer correctly?
				if firstteam == 2:
					if Team2_Correct:	
						Team2_Score += 1
					else:
						skip_section=True
						break
				
				update_score(Team1_Score,Team2_Score,background)
				
				#TODO: PLAY bing!!! sound
				#sleep(.10)
				#Tic sound
				pygame.mixer.music.play(0)
				while pygame.mixer.music.get_busy():
					pygame.time.Clock().tick(5)

			#Wait 5sec before jumping to the next step
			if not skip_section:
				sleep(5)

		else:
			update_score(Team1_Score,Team2_Score,background)
			sleep(5)
				
		#Update debug screen with the scores
		printxy(2,14,"Team 1 Score=%d" % (Team1_Score))
		printxy(2,15,"Team 2 Score=%d" % (Team2_Score))

		
	###########################################################
	# STEP 10: Announce the Results: The winner is....
	###########################################################

	#Clear debug screen
	os.system('clear')
	printxy(2,2,"=============================================================")
	
	
	if Team1_Score>Team2_Score:
		#Team 1 is the winner
		#Update debug screen
		printxy(2,4,'TEAM 1 is the Winner!!! with %d over %d' % (Team1_Score, Team2_Score))
		
		#Play video: Winner Team #1
		omx = OMXPlayer(screen_dict['gano_%s' %(team_color[1].lower())])
	
	elif Team1_Score<Team2_Score:
		#Team 2 is the winner
		#Update debug screen
		printxy(2,4,"TEAM 2 is the Winner!!! with %d over %d" % (Team2_Score, Team1_Score))
		
		#Play video: Winner Team #2
		omx = OMXPlayer(screen_dict['gano_%s' %(team_color[2].lower())])
	
	else:
		# It's a TIE!
		#Update debug screen
		printxy(2,4,"Tie : both team with Team 1=%d and Team 2=%d" % (Team1_Score, Team2_Score))
		
		#Play video: It's a Tie!
		omx = OMXPlayer(screen_dict['empate'])

	printxy(2,6,"=============================================================")
	printxy(2,8,question_answer)
	printxy(2,9,question_executed)
	
	sleep(5)
	omx.stop()
	
	#Render to a surface "background" to show final scores
	background = pygame.image.load(screen_dict['puntajes_finales']).convert_alpha()
		
	#Resize background to ensureit fills the screen
	background = pygame.transform.scale(background , SCREEN_RESOLUTION)
	update_score(Team1_Score,Team2_Score,background)
	
	
	#TODO: sleep duration mas be equal to the video length
	sleep(10)
	
	stop()
Ejemplo n.º 40
0
Archivo: tv.py Proyecto: emi420/undertv
 def waiting(self):
     self.waitingvideo = OMXPlayer(settings['VIDEO_WAITING_PATH'], '-o hdmi -b', start_playback=True) 
Ejemplo n.º 41
0
from pyomxplayer import OMXPlayer
from pprint import pprint
import time

omx = OMXPlayer('/home/pi/Videos/at.mp4')
pprint(omx.__dict__)

time.sleep(5)
print('toggling pause')
omx.toggle_pause()

time.sleep(5)
print('toggling pause')
omx.toggle_pause()

time.sleep(5)
print('stopping')
omx.stop()
Ejemplo n.º 42
0
 def skip(pin_num):
     i = i + 1
     player = OMXPlayer('/home/pi/Desktop/Music/' + temp2[i])
Ejemplo n.º 43
0
import os
from pyomxplayer import OMXPlayer

loop1 = OMXPlayer('/home/pi/videos/background.mp4',
                  '-o local',
                  start_playback=True)
loop2 = OMXPlayer('/home/pi/videos/Nature.mp4',
                  '-o local',
                  start_playback=True)
loop2.toggle_pause()

position = loop1.position / 1000000
if position > 12.8:
    loop1.toggle_pause()

sleep(2)
os.system(
    'pkill -9 -f "/usr/bin/omxplayer.bin -s /home/pi/videos/background.mp4 -o local"'
)
os.system(
    'pkill -9 -f "/bin/bash /usr/bin/omxplayer -s /home/pi/videos/background.mp4 -o local"'
)
sleep(2)
loop1 = OMXPlayer('/home/pi/videos/background.mp4',
                  '-o local',
                  start_playback=True)
loop1.toggle_pause()
Ejemplo n.º 44
0
from gpiozero import LED, Button
import time
import sys

# we'll use a button to advance the slide show
yButton = Button(6, pull_up=False, bounce_time=0.05)
# and an LED to make sure the button is working properly
yLed = LED(20)
yButton.when_pressed = yLed.on
yButton.when_released = yLed.off

# we'll use another button for quitting the program (since it runs fullscreen)
rButton = Button(19, pull_up=False, bounce_time=0.05)

# sets up the video player
omx = OMXPlayer('../movs/MechanicalPrinciples.mov')

try:
    # run this next section forever, until user stops the programme by pressing button
    while True:
        # play video if button is pressed and video player is currently paused
        if yButton.is_pressed and omx.paused:
            omx.toggle_pause()
        # pause video if button is not pressed and player is not paused
        if (not yButton.is_pressed) and (not omx.paused):
            omx.toggle_pause()

        # when quit button is pressed, stop player and quit programme
        if rButton.is_pressed:
            omx.stop()
            sys.exit(0)
Ejemplo n.º 45
0
class VideoStepper:
    def __init__(self):
        print 'Init VideoStepper'

        try:
            cfgFd = open(config_path, 'r')
            self.cfg = json.load(cfgFd)
            self.stepsNumber = len(self.cfg['steps'])
        except IOError:
            quit()

        # need pause if true
        self.isFirstVideoMovie = False
        self.isFirstVideoMovie2 = False

        if 'general' in self.cfg:
            if 'movies_path' in self.cfg['general']:
                self.movies_path = self.cfg['general']['movies_path']
            else:
                print 'Error: cfg not contain general/movies_path'
                quit()

            if 'baudrate' in self.cfg['general']:
                self.s_baudrate = self.cfg['general']['baudrate']
            else:
                self.s_baudrate = 19200

            if 'bytesize' in self.cfg['general']:
                self.s_bytesize = self.cfg['general']['bytesize']
            else:
                self.s_bytesize = 8

            if 'parity' in self.cfg['general']:
                self.s_parity = self.cfg['general']['parity']
            else:
                self.s_parity = 'N'

            if 'stopbits' in self.cfg['general']:
                self.s_stopbits = self.cfg['general']['stopbits']
            else:
                self.s_stopbits = 1

        else:
            print 'Error: cfg not contain general'
            quit()

        if 'map' not in self.cfg:
            print 'Error: cfg not contain map'
            quit()

        if 'steps' not in self.cfg:
            print 'Error: cfg not contain steps'
            quit()

        if 'steps_order' not in self.cfg:
            print 'Error: cfg not contain steps_order'
            quit()

        self.gpio = {}
        if 'gpio' in self.cfg:
            GPIO.setmode(GPIO.BCM)

            GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP)
            GPIO.add_event_detect(25, GPIO.RISING, callback=gpio_event, bouncetime=200)

            for idx, curGpio in enumerate(self.cfg['gpio']):
                gpioNum = curGpio['gpio']
                gpioStep = curGpio['step']

                self.gpio[gpioNum] = gpioStep

                GPIO.setup(gpioNum, GPIO.IN, pull_up_down=GPIO.PUD_UP)
                GPIO.add_event_detect(gpioNum, GPIO.FALLING, callback=gpio_event, bouncetime=200)

        self.currentStep = ""
        self.players = []
        self.currentPlayer = None
        self.nextStepPlayer = None
        self.stepIdForNextStepPlayer = ""
        self.goingToStep = False
        self.needFlash = False

        self.lock = Lock()

        self.playersThread = Thread(target=self.playFiles)
        self.playersThread.start()

        self.stepperThread = Thread(target=self.playStep)
        self.stepperThread.start()

    def playFiles(self):
        # try:
        #     pdb.set_trace()
        # except:
        #     pass

        curPlayer = None
        oldPlayer = None
        while True:
            self.lock.acquire()
            needStop = False
            if self.currentStep == "<STOP>":
                needStop = True
            elif not self.currentPlayer:
                self.lock.release()
                sleep(0.01)
                continue
            elif self.currentPlayer == curPlayer:
                # print 'not changed'
                self.lock.release()
                sleep(0.01)
                continue

            oldPlayer = curPlayer
            curPlayer = self.currentPlayer
            self.currentPlayer.set_volume(1)
            # oldPlayer = curPlayer
            self.lock.release()

            print 'currentPlayer changed, start it'

            # pdb.set_trace()
            # if self.needFlash:
            #     pyopengles.play()
            if not needStop:
                if not self.isFirstVideoMovie:
                    curPlayer.play()
                else:
                    self.isFirstVideoMovie = False

            # stop previous player (finished on last iteration) after start new player for smaller gap between them
            if oldPlayer:
                oldPlayer.stop()
                if needStop:
                    self.lock.acquire()
                    if self.currentStep == "<STOP>":
                        self.currentStep = ""
                    self.lock.release()


            # waiting whane self.currentPlayer changed
            # while not curPlayer.finished:
            #     self.lock.acquire()
            #     if curPlayer != self.currentPlayer:
            #         self.lock.release()
            #         break
            #
            #     self.lock.release()
            #     sleep(0.05)
        print 'playFiles thread terminated...'

    def getMoviePathByMovieId(self, movieId):
        if movieId not in self.cfg['map']:
            return ""

        return os.path.abspath(
            os.path.join(self.movies_path, self.cfg['map'][movieId])
        )

    def getSRTPathByMovieId(self, movieId):
        if movieId not in self.cfg['subtitles']:
            return ""

        return os.path.abspath(
            os.path.join(self.movies_path, self.cfg['subtitles'][movieId])
        )

    def doStep(self, step):
        print "doStep invoked"
        # search step cfg
        if step not in self.cfg['steps'] and step != "<STOP>":
            print 'Step %s definition not found' % step
            return

        # for doing step we alwayes need to create new instance of omxplayer,
        # cause we can't change currently plaing movie in the same instance
        # of omxplayer
        self.lock.acquire()
        self.currentStep = step
        print "GOING TO STEP %s" % self.currentStep
        self.lock.release()

    def playStep(self):
        # single step can contain multiple movies
        try:
            pdb.set_trace()
        except:
            pass
        curStepFirstPlayer = None
        curStepSecondPlayer = None
        step = ""
        layNum = 0
        while True:
            self.lock.acquire()
            # print "CURRENT STEP: %s" % self.currentStep
            if self.currentStep == "<STOP>":
                step = ""
                self.lock.release()
                sleep(0.01)
                continue

            if (not self.currentStep):
                self.lock.release()
                sleep(0.01)
                continue
            elif step == self.currentStep:
                self.lock.release()
                sleep(0.01)
                continue

            step = self.currentStep

            self.lock.release()

            # playing step
            currentStepNeedStop = False
            curStepFirstPlayer = None
            curStepSecondPlayer = None

            filesInStep = len(self.cfg['steps'][step])
            for idx, curFile in enumerate(self.cfg['steps'][step]):
                if currentStepNeedStop:
                    break

                movieId = curFile['movie']
                curFileLen = -1
                if 'length' in curFile:
                    curFileLen = curFile['length']

                isLoop = False
                if 'loop' in curFile:
                    isLoop = curFile['loop']

                needFlash = False
                if 'flash' in curFile:
                    needFlash = curFile['flash']

                movieFile = self.getMoviePathByMovieId(movieId)
                srtFile = self.getSRTPathByMovieId(movieId)

                if idx == 0 and self.nextStepPlayer:
                    if step == self.stepIdForNextStepPlayer:
                        curStepFirstPlayer = self.nextStepPlayer
                    else:
                        # next steps is different from what we planning (not next - something another, may be previous)
                        self.nextStepPlayer.stop()

                    self.nextStepPlayer = None
                    self.stepIdForNextStepPlayer = ""
                elif curStepSecondPlayer:
                    curStepFirstPlayer = curStepSecondPlayer
                    curStepSecondPlayer = None

                if not curStepFirstPlayer:
                    # layNum += 1
                    curStepFirstPlayer = OMXPlayer(
                        movieFile,
                        #args='-o hdmi -p' + ("" if not isLoop else ' --loop'),
                        args='-o ' + audio_output + ' -p --layer '+str(layNum) + ((' --subtitles ' + srtFile + subtitles_font_arg) if srtFile else ''),
                        start_playback=not self.isFirstVideoMovie
                    )
                    curStepFirstPlayer.set_volume(1)

                self.needFlash = needFlash

                self.lock.acquire()
                self.currentPlayer = curStepFirstPlayer
                self.lock.release()

                # if self.isFirstVideoMovie:
                #     self.isFirstVideoMovie = False

                # nextFilePrepared = False
                # prepare the next video file with own omxplayer for smallest
                # gap between them
                # sleep(0.4)
                nextFileInStep = None
                # needPauseForInitNextPlayer = False
                if idx < filesInStep-1:
                    nextFileInStep = self.cfg['steps'][step][idx+1]
                    nextMovieFile = self.getMoviePathByMovieId(nextFileInStep['movie'])
                    nextSrtFile = self.getSRTPathByMovieId(nextFileInStep['movie'])
                    if nextFileInStep:
                        sleep(1)
                        layNum += 1
                        curStepSecondPlayer = OMXPlayer(
                            nextMovieFile,
                            #args='-o hdmi' + ("" if not nextFileInStep['loop'] else ' --loop'),
                            args='-o ' + audio_output + ' -p --layer ' + str(layNum) + ((' --subtitles ' + nextSrtFile + subtitles_font_arg) if nextSrtFile else ''),
                            start_playback=False,
                            hidemode=False
                        )

                        # pause for audio up
                        # self.togglePause()
                        # sleep(0.06)
                        # self.togglePause()

                        #self.currentPlayer.increase_volume()
                        #sleep(0.07)
                        #self.currentPlayer.decrease_volume()

                        #curStepSecondPlayer.set_volume(0)
                        #layNum += 1
                        # needPauseForInitNextPlayer = True

                    print 'Next file in step PREPARED'
                elif idx == (filesInStep-1):
                    # prepare first movie in next step
                    nextStep = self.getNextStepId(step)
                    if nextStep:
                        nextFileInStep = self.cfg['steps'][nextStep][0]
                        nextMovieFile = self.getMoviePathByMovieId(nextFileInStep['movie'])
                        nextSrtFile = self.getSRTPathByMovieId(nextFileInStep['movie'])

                        if nextFileInStep:
                            sleep(1)
                            # self.nextStepPlayer = OMXPlayer(
                            layNum += 1
                            self.nextStepPlayer = OMXPlayer(
                                nextMovieFile,
                                #args='-o hdmi' + ("" if not nextFileInStep['loop'] else ' --loop'),
                                args='-o ' + audio_output + ' -p --layer '+str(layNum) + ((' --subtitles ' + nextSrtFile + subtitles_font_arg) if nextSrtFile else ''),
                                start_playback=False,
                                hidemode=False
                            )

                            # self.togglePause()
                            # sleep(0.06)
                            # self.togglePause()

                            #self.currentPlayer.increase_volume()
                            #sleep(0.07)
                            #self.currentPlayer.decrease_volume()

                            #self.nextStepPlayer.set_volume(0)
                            #layNum += 1
                            self.stepIdForNextStepPlayer = nextStep
                            # needPauseForInitNextPlayer = True

                        print 'First file in next step PREPARED'

                    # while self.currentPlayer and not self.currentPlayer.finished:
                # if needPauseForInitNextPlayer:
                #     sleep(0.1)

                isRewinding = False
                while True:
                    # check current step may was changed
                    self.lock.acquire()
                    # print "self.currentStep != step: %s" % (self.currentStep != step)
                    if self.currentStep != step:
                        currentStepNeedStop = True
                        if curStepSecondPlayer:
                            curStepSecondPlayer.stop()
                            curStepSecondPlayer = None
                            # layNum -= 1

                        self.lock.release()
                        break
                    else:
                        if curFileLen > 0 and self.currentPlayer.position >= curFileLen and not isRewinding:
                            if (isLoop):
                                self.currentPlayer.rewind()
                                isRewinding = True
                                print 'SEEK playing by manual'
                                # sleep(0.2)
                            else:
                                self.lock.release()
                                print 'STOP playing by manual'
                                # layNum -= 1
                                break
                        elif self.currentPlayer and self.currentPlayer.finished:
                            self.lock.release()
                            # layNum -= 1
                            break

                        if self.currentPlayer.position < curFileLen:
                            # just rewinded
                            isRewinding = False

                    self.lock.release()

                    # if self.currentPlayer._paused:
                    #     print "PAUSED"

                    # sleep(0.01)

            # self.lock.acquire()
            # if self.currentStep == step:
            #     print "CLEAR STEP ON STEP: %s" % step
            #     self.currentStep = ""
            # self.lock.release()

            # self.currentStep = None

    def pause(self, isPause):
        if not self.currentPlayer:
            return

        if isPause:
            self.currentPlayer.pause()
        else:
            self.currentPlayer.play()

        pass

    def togglePause(self):
        if not self.currentPlayer:
            return

        self.currentPlayer.toggle_pause()

    def getNextStepId(self, currentStep=""):
        if not currentStep:
            currentStep = self.currentStep

        nextStepFound = False
        nextStep = ""
        if not currentStep:
            nextStep = self.cfg['steps_order'][0]
        else:
            for step in self.cfg['steps_order']:
                if nextStepFound:
                    nextStep = step
                    break

                if step == currentStep:
                    nextStepFound = True

        return nextStep

    def next(self):
        nextStep = self.getNextStepId()

        if not nextStep:
            return

        # self.doStep(nextStep, False if self.getNextStepId(nextStep) else True)
        self.doStep(nextStep)

    def prev(self):
        prevStep = ""

        if not self.currentStep:
            prevStep = self.cfg['steps_order'][0]
        else:
            tmpStep = ""
            for step in self.cfg['steps_order']:
                if step == self.currentStep:
                    prevStep = tmpStep
                    break

                tmpStep = step

        if not prevStep:
            prevStep = self.cfg['steps_order'][0]
            #return

        # if self.currentStepNextPlayer:
        #     self.currentStepNextPlayer.stop()
        #     self.currentStepNextPlayer = None
        if self.nextStepPlayer:
            self.nextStepPlayer.stop()
            self.nextStepPlayer = None

        self.doStep(prevStep)

    def gotoStep(self, step):
        if self.goingToStep:
          return

        self.goingToStep = True

        if self.isFirstVideoMovie2:
            self.isFirstVideoMovie2 = False

        self.doStep("<STOP>")

        while True:
            self.lock.acquire()
            curStep = self.currentStep
            self.lock.release()

            if not curStep:
                break

            sleep(0.01)

        self.doStep(step)

        self.goingToStep = False


    def stop(self):
        self.doStep("<STOP>")
Ejemplo n.º 46
0
 def test_paused_at_startup(self):
     mock_process = Mock()
     mock_process.readline = Mock(return_value=EXAMPLE_OMXPLAYER_OUTPUT)
     mock_spawn = Mock(return_value=mock_process)
     player = OMXPlayer("", _spawn=mock_spawn)
     self.assertTrue(player.paused)