Ejemplo n.º 1
0
def playTheme(fileName):
	output('speaker',1)
	player = Player()
	player.loadfile(fileName)
	# Terminate MPlayer
	player.quit()	
	output('speaker',0)
Ejemplo n.º 2
0
class SpdifPlayback(WorkflowTestFixture):
    def setUpFixture(self):
        self.zone = self.get_testbed_device_by_model(SOUNDBAR)
        self.verifyTrueOrStop(self.zone.diag.is_toslink_connected(),
                              'TOSLINK should be connected')
        self.mplayer = Player(args=MPLAYER_ARGS)

    def tearDownFixture(self):
        self.mplayer.stop()
        self.mplayer.quit()

    def _is_stream_type_expected(self):
        """
        Verifies TOSLINK Stream Type is expected

        :return: Is Stream Type expected?
        :rtype: :obj:`bool`
        """
        return self.zone.diag.get_toslink_stream_type() == EXPECTED_STREAM_TYPE

    def test_spdif_playback(self):
        """
        Verifies SPDIF playback by checking TOSLINK Stream Type 
        """
        self.mplayer.loadfile(TRACK)
        wait_until_true(lambda: self._is_stream_type_expected(),
                        timeout_seconds=10,
                        reason="Timed out waiting for expected stream type")
Ejemplo n.º 3
0
def start_playing(uuid, ytid):
	global current_uuid, should_be_paused, player
	if current_uuid is not None:
		stop_playing()
	if player is None:
		player = Player(args=player_args)
	assert player.filename is None
	if os.path.exists(path_for(ytid)):
		current_uuid = uuid
		player.loadfile(path_for(ytid))
		should_be_paused = False
Ejemplo n.º 4
0
class MPlayer(object):
    def __init__(self, *args, **kwargs):
        self.argparser = None
        self.exit = False
        self.paused = False
        self.player = Player()

    def set_argparser(self, argparser):
        self.argparser = argparser

    def start(self, *args, **kwargs):
        pass

    @property
    def is_playing(self):
        if self.player.filename and not self.paused:
            status = True
        else:
            status = False
        return status

    def play(self, path, track, block=True):
        self.player.loadfile(path)
        self.player.pause()
        time.sleep(3)
        if block:
            while self.player.filename:
                if self.exit:
                    break
                try:
                    time.sleep(0.1)
                except KeyboardInterrupt:
                    pass

    def pause(self):
        if self.is_playing:
            self.paused = True
            self.player.pause()

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

    def resume(self):
        if not self.is_playing:
            self.pause = False
            self.player.pause()

    def shutdown(self):
        if self.player.is_alive():
            self.player.quit()
Ejemplo n.º 5
0
def start_playback(songs_list,randomize_songs):
    """
    Initalizes the player and begins playback.
    Player must be assigned else it's garbage collected.
    """

    Player.cmd_prefix = CmdPrefix.PAUSING_KEEP
    player = Player('-loop -1')
    
    if randomize_songs:
        rand_song= randint(0,len(songs_list)-1)
        player.loadfile(songs_list[rand_song])
    else:
        player.loadfile(songs_list[0])
    
    return player
Ejemplo n.º 6
0
def start_playback(songs_list, randomize_songs):
    """
    Initalizes the player and begins playback.
    Player must be assigned else it's garbage collected.
    """

    Player.cmd_prefix = CmdPrefix.PAUSING_KEEP
    player = Player("-loop -1")

    if randomize_songs:
        rand_song = randint(0, len(songs_list) - 1)
        player.loadfile(songs_list[rand_song])
    else:
        player.loadfile(songs_list[0])

    return player
Ejemplo n.º 7
0
class Sound(object):
    """
    A Sound object is a simple abstraction of an underlying sound that can be
    played, stopped, etc.
    """
    def __init__(self, path, volume=100):
        self.path = path
        # We need to set the volume when creating the mplayer process. If we
        # don't, the sound would start playing at 100% for about 1 sec before
        # the actual volume gets applied
        self.player = Player(stdout=PIPE, stderr=PIPE,
                             args=('-volume {0}'.format(volume)))
        self.player.loadfile(self.path)
        # Pause the stream so we can't do something else before calling play()
        self.player.pause()

    def play(self, loop=False):
        if loop:
            self.player.loop = 0

        self.player.pause()

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

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

    def get_volume(self):
        return self.player.volume

    def set_volume(self, volume):
        self.player.volume = volume

    def get_duration(self):
        return self.player.length

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

    def __del__(self):
        self.destroy()
Ejemplo n.º 8
0
#!/usr/bin/env python
import os
from mplayer import Player

player = Player()
pathToFile = os.path.join(os.path.dirname(__file__), "Recording.m4a")
player.loadfile(pathToFile)

# os.system ('omxplayer -o local /home/pi/Documents/Rasp/Recording.m4a')


# os.system ('omxplayer -o local' + file)
Ejemplo n.º 9
0
class camlapse(object):
	
 
	def __init__(self, pf): # inits with a file name, if it exists, loads the project, else makes a new one

		pDir = os.path.dirname(os.path.realpath(__file__))+'/'+pf

		subprocess.call("killall PTPCamera", shell=True)

		self.player = Player()
		self.pname = pf
		self.WEEK_FPH = [1,24,60,120,360,720,1440,2880,5760,11520,23040,46080,86400,86400]

		self.lastFrame = datetime.now()
		self.spf = 1
		self.fph = 1
		self.videoSpeed = 1.0
		self.currentVideoSpeed = 0.009

		if os.path.isdir(pDir):
			print "Loading project : %s" % (pf)
			self.loadProject(pf)
		else:
			print "New project : %s" % (pf)
			self.newProject(pf)

	#---------------------------------------------------------------------------
	# Saving and loading
	#---------------------------------------------------------------------------
	def newProject(self, pf):
		# create project folder and support subfolders
		self.projectDir = os.path.dirname(os.path.realpath(__file__))+'/'+pf
		self.pictureDir = self.projectDir+'/'+'pictures'
		self.videoDir = self.projectDir+'/'+'videos'
		self.tmpDir = self.projectDir+'/'+'tmp'
		cmd = 'mkdir ' + self.projectDir
		subprocess.call(cmd, shell=True)
		cmd = 'mkdir ' + self.pictureDir
		subprocess.call(cmd, shell=True)
		cmd = 'mkdir ' + self.videoDir
		subprocess.call(cmd, shell=True)
		cmd = 'mkdir ' + self.tmpDir
		subprocess.call(cmd, shell=True)

		self.frameIndex = 0

		self.startTime = datetime.now()
		self.newXML()

		# do enough to have the first video
		self.doLapse()
		self.doLapse()
		self.doLapse()
		# begin video playback
		self.startVideoPlayback()


	def loadProject(self, pf):

		self.projectDir = pf
		self.pname = pf
		self.pictureDir = self.projectDir+'/'+'pictures'
		self.videoDir = self.projectDir+'/'+'videos'
		self.tmpDir = self.projectDir+'/'+'tmp'
		self.loadXML()

		path, dirs, files = os.walk(self.pictureDir).next()
		self.frameIndex = len(files) + 1
		# begin video playback
		self.startVideoPlayback()

	def saveVideo(self, saveFolder):
		return True # create a copy of the video file to a specific directory

	#---------------------------------------------------------------------------
	# File Management
	#---------------------------------------------------------------------------
	def getPhotoFile(self, id):
		return self.pictureDir+'/'+'%s_photo_%d.jpg' % (self.pname,id)

	def getVideoFile(self):
		return self.videoDir+'/'+'%s_video.mpg' % (self.pname)

	def getVideoFrameFile(self):
		return self.tmpDir+'/'+'%s_videoFrame.mpg' % (self.pname)

	def getXMLfile(self):
		return self.projectDir+'/'+'%s_data.xml' % (self.pname)

	#---------------------------------------------------------------------------
	# XML parts
	#---------------------------------------------------------------------------
	def newXML(self):
		root = ET.Element("clProject")
		sd = ET.SubElement(root, "time")
		sd.set('startTime', self.startTime.strftime("%Y-%m-%d %H:%M:%S"))
		fi = ET.SubElement(root,"stats")
		fi.set('frameCount', str(self.frameIndex))
		self.tree = ET.ElementTree(root)
		self.tree.write(self.getXMLfile())# , pretty_print=True)

	def loadXML(self):
		self.tree = ET.parse(self.getXMLfile())
		sd = self.tree.find('time')
		self.startTime = datetime.strptime(sd.get('startTime'),"%Y-%m-%d %H:%M:%S")

	def updateXML(self):
		#fi = self.tree()
		self.tree.write(self.getXMLfile())#, pretty_print=True)

	#---------------------------------------------------------------------------
	# Camera control
	#---------------------------------------------------------------------------

	def takePhoto(self, id):
		if not os.path.isfile(self.getPhotoFile(id)):
			cmd = 'gphoto2 --quiet --filename %s --capture-image-and-download' % (self.getPhotoFile(id))
			subprocess.call(cmd, shell=True)

	#---------------------------------------------------------------------------
	# Video process
	#---------------------------------------------------------------------------

	def makeVideoFrame(self, id):
		if os.path.isfile(self.getVideoFrameFile()):
			cmd = 'rm '+ self.getVideoFrameFile()
			subprocess.call(cmd, shell=True)
		cmd = 'ffmpeg -loglevel panic -f image2 -i %s -r 25 %s' % (self.getPhotoFile(id), self.getVideoFrameFile())
		subprocess.call(cmd, shell=True)


	def addFrameToVideo(self):
		if not os.path.isfile(self.getVideoFrameFile()):
			cmd = 'mv %s %s' % (self.getVideoFrameFile(), self.getVideoFile()) #if no video exists create one
		else:
			cmd = 'cat %s >> %s' % (self.getVideoFrameFile(), self.getVideoFile())
		subprocess.call(cmd, shell=True)


	#---------------------------------------------------------------------------
	# Video Playback
	#---------------------------------------------------------------------------
	def startVideoPlayback(self):
		self.player.loadfile(self.getVideoFile())
		print "Video File Loaded"
		self.player.pause()
		self.player.fullscreen = 1
		self.player.loop = 0
		self.updateVideo()

	def updateVideo(self):
		self.getPlaybackSpeed()
		if self.videoSpeed > 0.01: # fast enough for mplayer to do the playback
			if self.videoSpeed - self.currentVideoSpeed > 0.0001:
				self.player.pause(0)
				self.player.speed = self.videoSpeed
				self.currentVideoSpeed = self.videoSpeed
				print "Video speed updated"
		else: # step the frames
			self.stepVideo()

	def stepVideo(self):
		td = datetime.now() - self.lastFrame
		if td.seconds > self.spf:
			self.player.pause(0)
			self.player.frame_step()
			self.lastFrame = datetime.now()


	def getPlaybackSpeed(self):
		total = self.getWeek() # 3.5 weeks
		weeks = int(total)
		lrp = total - weeks
		if weeks < len(self.WEEK_FPH)-1:
			a = self.WEEK_FPH[weeks]
			b = self.WEEK_FPH[weeks+1]
			self.fph = self.lerp(a,b,lrp)
		else: self.fph = self.WEEK_FPH[len(self.WEEK_FPH)-1]
		self.spf = 3600/self.fph # seconds per frame
		self.videoSpeed = self.fph/float(90000)  # speed scaler for 25fps


	def lerp(self, a, b, l):
		return a+((b-a)*l)

	#---------------------------------------------------------------------------
	# time stuff
	#---------------------------------------------------------------------------

	def getWeek(self): #return interger of the week!
		td = datetime.now() - self.startTime
		return (td.days/7)+float(td.seconds)/604800
		# number of weeks + current week progress seconds in a week 604800


	#---------------------------------------------------------------------------
	# Accesors
	#---------------------------------------------------------------------------

	def getFrameCount(self):
		return self.frameIndex

	def getTimeElapsed(self):
		return True # calculate and return months/days h:m:s elapsed

	def printStartTime(self):
		print self.startTime

	#---------------------------------------------------------------------------
	# Modifiers
	#---------------------------------------------------------------------------


	#---------------------------------------------------------------------------
	# main Loops
	#---------------------------------------------------------------------------
	def main(self):
		while True:
			self.doLapse()
			self.updateVideo()


	def doLapse(self):
		self.takePhoto(self.frameIndex)
		self.makeVideoFrame(self.frameIndex)
		self.addFrameToVideo()
		self.frameIndex += 1
Ejemplo n.º 10
0
class MediaPlayer:
    def __init__(self, settings):
        self.settings = settings
        self.player = False
        self.effect = False
        self.spotify = None

        self.alarm_media = settings.get("alarm_media")

        if self.alarm_media == "Spotify":
            log.debug("Loading Spotify")
            self.spotify = SpotifyThread.SpotifyThread(settings)
            self.spotify.setDaemon(True)
            self.spotify.start()
        #     #self.spotify.setDaemon(True)
        #     # log.debug("Spotify event loop")
        #     # self.spotify.event_loop = self.spotify.EventLoop(self.session)
        #     # self.spotify.event_loop.start()
        #     #self.spotify.login(settings.get("spotify_user"), settings.get("spotify_pass"))

    def playerActive(self):
        # log.debug("playerActive: {0}".format(self.player != False))
        if self.alarm_media == "Spotify":
            if self.spotify.spotify.session.player.state == "playing":
                return True
            else:
                return False

        else:
            if self.player != False:
                return True
            else:
                return False
        # return self.player != False

    def soundAlarm(self, snoozing=False):
        log.info("soundAlarm: Playing alarm")

        if self.alarm_media == "Spotify":
            self.playSpotify(snoozing)
        else:
            self.playStation()

            log.debug("Verifying Radio is playing")
            # Wait a few seconds and see if the mplayer instance is still running
            time.sleep(self.settings.getInt("radio_delay"))

            # Fetch the number of mplayer processes running
            processes = subprocess.Popen(
                'ps aux | grep mplayer | egrep -v "grep" | wc -l', stdout=subprocess.PIPE, shell=True
            )
            num = int(processes.stdout.read())

            if num < 2 and self.player is not False:
                log.error("Radio fail: Could not find mplayer instance, playing panic alarm")
                self.stopPlayer()
                time.sleep(2)
                self.playMedia(PANIC_ALARM, 0)
            else:
                log.debug("Radio success")

    def playSpotify(self, snoozing=False):
        log.debug("playSpotify: ")
        # self.spotify = SpotifyThread()
        if snoozing:
            log.debug("resuming")
            self.spotify.resume()
        else:
            log.debug("play")
            # play_thread = self.spotify.play()
            # play_thread.join()
            self.spotify.play()
        log.debug("leaving playSpotify: ")

    def playStation(self):
        log.debug("playStation: ")
        station = self.settings.get("station")

        log.info("Playing station %s", station)
        self.player = Player()
        self.player.loadlist(station)
        self.player.loop = 0

    def playMedia(self, file, loop=-1):
        log.info("playMedia: Playing file %s", file)
        self.player = Player()
        self.player.loadfile(file)
        self.player.loop = loop

    # Play some speech. None-blocking equivalent of playSpeech, which also pays attention to sfx_enabled setting
    def playVoice(self, text):
        log.debug("playVoice (non-blocking): {0}".format(text))
        if self.settings.get("sfx_enabled") == 0:
            # We've got sound effects disabled, so skip
            log.info("Sound effects disabled, not playing voice")
            return
        log.info("Playing voice: '%s'" % (text))
        play = subprocess.Popen('../speech/googletts "%s"' % (text), shell=True)

    # Play some speech. Warning: Blocks until we're done speaking
    def playSpeech(self, text):
        log.debug("playSpeech (blocking): {0}".format(text))
        if self.settings.get("sfx_enabled") == 0:
            log.info("Playing speech: '%s'" % (text))
            play = subprocess.Popen('../speech/googletts "%s"' % (text), shell=True)
            play.wait()

    def stopPlayer(self):
        log.debug("stopPlayer: ")
        if self.player:
            self.player.quit()
            self.player = False
            log.info("Player process terminated")
Ejemplo n.º 11
0
class MplayerAudio():
    def __init__(self, config):
        self.config = config
        self.state = u'stopped'
        self.uri = None
        self.player = Player()

    def emit_data(buffer_):
        return Wrap(False)

    def emit_end_of_stream(self):
        pass

    def get_mute(self):
        return Wrap(self.player.mute)

    def get_position(self):
        return Wrap(1)
    '''
    def get_volume(self):
        return Wrap(int(self.player.volume))
        return Wrap(0)
    '''

    def pause_playback(self):
        if not self.player.paused:
            self.player.pause()
            self.state = u'paused'
        return Wrap(True)

    '''
    def prepare_change(self):
        pass
    '''

    def set_appsrc(self, caps, need_data=None,
                   enough_data=None, seek_data=None):
        pass

    def set_metadata(self, track):
        return Wrap(False)

    def set_mute(self, mute):
        self.player.mute = mute
        return Wrap(True)

    def set_position(self, position):
        return Wrap(False)

    def set_uri(self, uri):
        self.uri = uri
        return Wrap(True)

    def set_volume(self, volume):
        #  self.player.volume = volume
        return Wrap(True)

    def start_playback(self):
        if self.player.paused:
            self.player.pause()
        if not self.player.filename:
            self.player.loadfile(self.uri.replace('mplayer:', ''))
        self.state = u'playing'
        return Wrap(True)

    def stop_playback(self):
        self.player.stop()
        self.state = u'stopped'
        return Wrap(True)

    def prepare_change(self):
        self.player.stop()
        return Wrap(True)

    def set_about_to_finish_callback(self, callback):
        pass
Ejemplo n.º 12
0
class alarm:

    dowlist = 'MO,TU,WE,TH,FR,SA,SU'.split(',')
    dow = {d:i for i,d in enumerate(dowlist)}
    def  __init__(self, name, time, days = ('MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'), date = None, path = './playlist/',
                  volume = 40, active = True, color_onset = 300, duration = -1, color = 'FFFFFF' ):
        '''define an alarm. at the time of the alarm, a media file is played
        required parameters is time (datetime.time)
        optional parameters days, the days of the week for the alarm.
                            days is one or more of 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'
                            date is the date for a specific alarm. date overrides the days parameter
                            path is the path to media files
                            if active is True, the alarm will play otherwise it will not.  '''

        self.name =           name
        self.time =           time
        self.days =           days
        self.date =           date
        self.repeating =      True if date == None else False
        self.active =         active
        self.volume =         volume
        self.path =           path +'/'if path[-1] != '/' else path # add a / to the end of the path if not present
        self.color_onset =    color_onset # onset is the time before the alarm for sunrise
        self.duration =       duration # duration of the alarm. -1 is manual off only
        self.color =          color
        self.bulb_ip =        '192.168.1.162'

        # these variables are not passed when initiating the alarm, but are used for housekeeping

        self.chkbox =         {d:b for b,d in zip(('checked' if t in self.days else '' for t in self.dowlist),self.dowlist)}
        # used by the module web.py to format the ceckboxes for the recurrence
        self.playing =        False
        self.track =          None


    def update_alarm(self, **kwargs):
        '''update the the alarm. the function takes 0 or more inputs from the list
           name, time, days, date, path and repeating
        '''
        self.name = kwargs.get('name', self.name)
        self.time = kwargs.get('time', self.time)
        self.days = kwargs.get('days', self.days)
        self.date = kwargs.get('date', self.date)
        self.repeating = kwargs.get('repeating', self.repeating)
        self.path = kwargs.get('path', self.path)
        self.volume = kwargs.get('volume', self.volume)
        self.active = kwargs.get ('active', self.active)
        self.color = kwargs.get('color', self.color)
        self.color_onset = kwargs.get('color_onset', self.color_onset)
        self.duration = kwargs.get('duration', self.duration)

        # housekeeping
        if self.path[-1] != '/':
            self.path += '/'
        self.chkbox =    {d:b for b,d in zip(('checked' if t in self.days else '' for t in self.dowlist),self.dowlist)}
        
        self.volume = max(min(100, self.volume), 0) # volume should be between 0 and 100
         

    def next_alarm(self, now):
        '''alarm.next(now) returns the next occurence of an alarm after the input
        eg alarm(time(10,0,0)).next(datetime(2015,1,1,11,0,0))
        -> the next alarm at 10am if today is 11:00AM on Jan 1st 2015
        will return
        datetime(2015,1,2,10,0,0) -> 10:00 AM on Jan 2nd 2015'''

        #offset now by 60 seconds so that next(now) = now
        now += datetime.timedelta(0,-60)

        # first determine the start date...
        # which is either a specific date (ie self.date != None
        # tomorrow (if now.time is past alarm.time
        # or today (in all other cases)
        if not self.active:
            return None
        if not self.repeating:
            date = self.date
            if self.date == None or datetime.datetime.combine(date, self.time) < now:
                return None
        elif now.time() > self.time:
            date = now.date() + datetime.timedelta(1)
        else:
            date = now.date()

        next_date = datetime.datetime.combine(date, self.time)

        #map the weekday numbers to the days in alarm.days, so that 'MO' = 0, TU = 1
        #then increment the current date until the current dow matches a day in alarm.days

        wkdays = set(alarm.dow[x] for x in self.days)
        while next_date.weekday() not in wkdays:
            next_date += datetime.timedelta(1)
        return next_date

    def generate_playlist(self, path=None, ext = ('.mp3','.wav','.flac')):
        '''generates a list of files in path
        that ends with extension ext (default = .mp3, .wav and .flac'''
        if path == None:
            path = self.path
        return sorted(list(filter(lambda x: x.endswith(ext), os.listdir(path))))

    def play(self):

        playlist = self.generate_playlist()
        path = self.path
        self.player = Player()
        self.playing = True
        while len(playlist) >0:
            track = playlist.pop(0)
            self.player.loadfile(path+track)
            i=0
            while self.player.time_pos == None:
                time.sleep(0.1)
                print ('loading', path+track, i, end='\r')
                i+=1
            print()
            self.player.volume = self.volume
            while self.player_active():
                print (path+track, self.player.time_pos, end='\r')
                time.sleep(1)
        self.stop()



    def wakeup_light(self):
        r, g, b = webcolors.hex_to_rgb('#'+self.color)
        bulb = ledenet_api.bulb(self.bulb_ip)
        bulb.gradual(r,g,b,self.color_onset)


    def player_active(self):
        if self.playing:
            return self.player.time_pos != None
        else:
            return False


    def stop(self):
        self.turn_off_light()
        self.track = None
        if self.playing:
            self.playing = False
            self.player.quit()

    def turn_off_light(self):
        bulb = ledenet_api.bulb(self.bulb_ip)
        bulb.turn_off()
Ejemplo n.º 13
0
class MediaPlayer:
    def __init__(self):
        self.settings = Settings.Settings()
        self.player = False
        self.effect = False

    def playerActive(self):
        return self.player != False

    def soundAlarm(self, alarmThread):
        log.info("Playing alarm")
        self.playStation()
        log.debug("Alarm process opened")

        # Wait a few seconds and see if the mplayer instance is still running
        time.sleep(self.settings.getInt('radio_delay'))

        if alarmThread.isSnoozing() or alarmThread.getNextAlarm() is None:
            # We've snoozed or cancelled the alarm, so no need to check for player
            log.debug(
                "Media player senses alarm already cancelled/snoozed, so not checking for mplayer instance"
            )
            return

        # Fetch the number of mplayer processes running
        processes = subprocess.Popen(
            'ps aux | grep mplayer | egrep -v "grep" | wc -l',
            stdout=subprocess.PIPE,
            shell=True)
        num = int(processes.stdout.read())

        if num < 2 and self.player is not False:
            log.error("Could not find mplayer instance, playing panic alarm")
            self.stopPlayer()
            time.sleep(2)
            self.playMedia(PANIC_ALARM, 0)

    def playStation(self, station=-1):
        if station == -1:
            station = self.settings.getInt('station')

        station = Settings.STATIONS[station]

        log.info("Playing station %s", station['name'])
        self.player = Player()
        self.player.loadlist(station['url'])
        self.player.loop = 0

    def playMedia(self, file, loop=-1):
        log.info("Playing file %s", file)
        self.player = Player()
        self.player.loadfile(file)
        self.player.loop = loop

    # Play some speech. None-blocking equivalent of playSpeech, which also pays attention to sfx_enabled setting
    def playVoice(self, text):
        if self.settings.get('sfx_enabled') == 0:
            # We've got sound effects disabled, so skip
            log.info("Sound effects disabled, not playing voice")
            return
        path = self.settings.get("tts_path")
        log.info("Playing voice: '%s' through `%s`" % (text, path))
        play = subprocess.Popen('echo "%s" | %s' % (text, path), shell=True)

    # Play some speech. Warning: Blocks until we're done speaking
    def playSpeech(self, text):
        path = self.settings.get("tts_path")
        log.info("Playing speech: '%s' through `%s`" % (text, path))
        play = subprocess.Popen('echo "%s" | %s' % (text, path), shell=True)
        play.wait()

    def stopPlayer(self):
        if self.player:
            self.player.quit()
            self.player = False
            log.info("Player process terminated")
Ejemplo n.º 14
0
def main():
    try:
        print("Selecting stream...")
        sys.stdout.flush()
        if os.path.isfile(alt_music_list_path):
            alt_music_list_file = open(alt_music_list_path, 'r')
            alt_music_list = [f.strip() for f in alt_music_list_file.readlines()]
            print("Alternative list available")
            sys.stdout.flush()
        else:
            alt_music_list = []
        if store in alt_music_list:
            CODE = 'f6403f66f656451f8fcbf4b4fe881d9b'
        else:
            CODE = '79c6519c9d1b46fc8d6d341d92f4eb4d'
        CURL = commands.getoutput("curl -s 'https://api.rebrandly.com/v1/links/%s' -H 'apikey: 77a44fcac24946679e800fadc4f84958'" % CODE)
        JSON = json.loads(CURL)
        STREAM = JSON["destination"]
        print("Checking stream...")
        sys.stdout.flush()
        if int(urllib.urlopen(STREAM).getcode()) != 200:
            raise Exception("Stream not available. Restarting")
        print("Starting player...")
        sys.stdout.flush()
        player = Player(args=('-ao alsa:device=hw=1.0'))
        player.loadfile(STREAM)
        print("Playing %s" % STREAM)
        sys.stdout.flush()
        print("Checking for announcements...")
        sys.stdout.flush()
        announcements = []
        if os.path.exists(announcements_lang_path):
            announcements = [os.path.join(announcements_lang_path, f) for f in os.listdir(announcements_lang_path) if not f.startswith('.') and os.path.isfile(os.path.join(announcements_lang_path, f))]
        # announcements_date_file = "%s.mp3" % datetime.today().strftime('%Y-%m-%d')
        # if country == 'sweden' and os.path.exists(announcements_date_path) and os.path.isfile(os.path.join(announcements_date_path, announcements_date_file)):
        #     announcements.append(os.path.join(announcements_date_path, announcements_date_file))
        if announcements:
            print("Announcements found for %s" % country)
            sys.stdout.flush()
            print("Waiting for cache. Sleeping for 2 mins")
            sys.stdout.flush()
            sleep(120)
            while True:
                for announce in announcements:
                    for n in range(GAP):
                        if not player.is_alive():
                            raise Exception("Player not playing. Restarting")
                        if player.filename is None:
                            raise Exception("No internet connected. Restarting")
                        sleep(1)
                    player.pause()
                    player_announce = Player(announce)
                    sleep(1)
                    duration = int(math.ceil(player_announce.length))
                    if (duration > 30):
                        duration -= 27
                    else:
                        duration -= 1
                    sleep(duration)
                    player_announce.quit()
                    player.pause()
        else:
            print("No announcements found for %s" % country)
            sys.stdout.flush()
            print("Waiting for cache. Sleeping for 2 mins")
            sys.stdout.flush()
            sleep(120)
            while True:
                if not player.is_alive():
                    raise Exception("Player not playing. Restarting")
                if player.filename is None:
                    raise Exception("No internet connected. Restarting")
                sleep(1)
    except Exception as e:
        try:
            player.quit()
        except:
            pass
        print(e)
        sys.stdout.flush()
        main()
Ejemplo n.º 15
0
class PlayerThread(threading.Thread):
    def __init__(self, subsonic, msg_queue):
        # Read config and setup the player accordingly
        self.config = read_config()

        self.download_queue = []

        subsonic = Subsonic()
        self.subsonic = subsonic.connection
        self.mplayer = MPlayer(
            args=("-really-quiet", "-msglevel", "global=6", "-nolirc")
        )
        self.mplayer.stdout.connect(self._handle_data)

        self.msg_queue = msg_queue

        super(PlayerThread, self).__init__()

    def _handle_data(self, data):
        # Handle the stdout stream coming back from MPlayer.
        if data.startswith('EOF code:'):
            if data.split(": ")[1] == "1":
                # EOF Code: 1 means that the song finished playing
                # by itself. Therefore we want to try to play the
                # next song in the queue.
                self.msg_queue.put("EOF")

    def _get_stream(self, song_id):
        return self.subsonic.stream(song_id)

    def _get_song(self, song_id):
        song_file = os.path.join(MUSIC_CACHE_DIR, "%s.mp3" % song_id)
        if os.path.exists(song_file):
            logger.info("The song with id %s was found in the cache" % song_id)
            # Check if file already exists in cache
            if not os.path.exists(MUSIC_CACHE_DIR):
                # Make sure the cache dir is present.
                os.makedirs(MUSIC_CACHE_DIR)
            if not song_id in self.download_queue:
                # Check if the song is not already downloading
                logger.debug("Downloading song with id: %s" % song_id)
                self.download_queue.append(song_id)
                try:
                    stream = self._get_stream(song_id)
                    f = open(song_file, "wb")
                    f.write(stream.read())
                    f.close()
                    logger.debug("Finished downloading song with id: %s" % song_id)
                except Exception as e:
                    logger.error(
                        "Could not download song with id: %s - Error was: %s" % (
                            song_id, e
                        )
                    )
                self.download_queue = [
                    x for x in self.download_queue if x != song_id
                ]
            else:
                logger.info(
                    "Song with id %s is already in download queue. \
                    Doing nothing." % song_id
                )
                # TODO: Handle this. Should we wait here for a little bit
                # and see if it finishes downloading?
                # At this point, if it clashes, it gets stuck in stopped state.

        return song_file

    def play_song(self, song_id):
        song_file = self._get_song(song_id)
        self.mplayer.stop()
        self.mplayer.loadfile(song_file)

        # Hacky, but needed to work. Check if Linux or Darwin, if so
        # also play the file after loading it. On OS X, pressing play
        # is not needed.
        if "linux" or "darwin" in platform:
            self.mplayer.pause()

    def play(self):
        if self.is_paused():
            self.mplayer.pause()

    def pause(self):
        self.mplayer.pause()

    def stop(self):
        self.mplayer.stop()

    def seek(self, timedelta):
        if not self.is_stopped() and isinstance(timedelta, int):
            time_pos = self.mplayer.time_pos
            length = self.mplayer.length
            new_time_pos = time_pos + timedelta
            if new_time_pos < 0:
                new_time_pos = 0
            elif new_time_pos > length:
                # So we have seeked passed the length of the song?
                # Play next song.
                self.msg_queue.put("EOF")

            self.mplayer.time_pos = new_time_pos

    def player_state(self):
        if self.is_playing():
            return "Playing"
        elif self.is_paused():
            return "Paused"
        else:
            return "Stopped"

    def is_playing(self):
        return bool(self.mplayer.filename and not self.mplayer.paused)

    def is_paused(self):
        return bool(self.mplayer.filename and self.mplayer.paused)

    def is_stopped(self):
        return bool(not self.mplayer.filename)

    def progress(self):
        ret = None
        if self.mplayer.time_pos:
            try:
                ret = {
                    "percent": self.mplayer.percent_pos,
                    "time": int(self.mplayer.time_pos),
                    "length": int(self.mplayer.length),
                }
            except:
                ret = {
                    "percent": 0,
                    "time": 0,
                    "length": 0,
                }
        return ret

    def quit(self):
        self.mplayer.quit()
Ejemplo n.º 16
0
class MusicPlayer(object):

    def __init__(self):
        self.playlist = []                  # Array of all tracks
        self.playlist_id = 0                # Id of playlist
        self.current_track_index = 0        # Index of current song
        self.player = Player()              # MPlayer instance
        self.webclient = Webclient()        # Client for WebInterface
        self.mobileclient = Mobileclient()  # Client for MobileInterface
        self.timer = None                   # Timer to start next track
        self.deviceid = 0                   # DeviceId to use
        self.playtype = PlayType.LINEAR     # LINEAR or SHUFFLE

    def login(self, username, password):
        """ Login to Google Music.

        Keyword arguments:
        username -- the username
        password -- the password

        Returns:
        True if successful else False

        """

        # If either the web client or the mobile client failed to login return False
        if not self.webclient.login(username, password) or not self.mobileclient.login(username, password):
            return False

        # Use first found devices as ID
        devices = self.webclient.get_registered_devices();

        # Convert HEX to INT
        self.deviceid = int(devices[0]['id'], 16)

        return True

    def load_playlist(self, playlist_name):
        # Load playlist
        for playlist in self.mobileclient.get_all_user_playlist_contents():
            if playlist['name'] == playlist_name:
                for track_obj in playlist['tracks']:
                    track_obj['track']['id'] = track_obj['id']
                    self.playlist.append(track_obj['track'])

                # Set playlist_id
                self.playlist_id = playlist['id']
                break;

        # If playlist has not been found, create it
        if self.playlist_id == 0:
            self.playlist_id = self.mobileclient.create_playlist(playlist_name)

    def add_track_to_playlist(self, track):
        """ Append a track to the end of playlist

        Keyword arguments:
        track -- a dictionary containing the track informations

        """
        track_id = self.mobileclient.add_songs_to_playlist(self.playlist_id, track['nid'])[0]
        track['id'] = track_id
        self.playlist.append(track)

        # Notify all clients about the new track
        factory.forwarder.dispatch(PLAYLIST_EVENT_TRACK_ADDED, json.dumps(track))

    def remove_track_from_playlist(self, track_id):
        """ Removes a track from the playlist

        Keyword arguments:
        track_id -- The id of the track to remove

        """
        self.mobileclient.remove_entries_from_playlist(track_id)

        index_to_remove = self._find_index_of_track_id(track_id)

        del self.playlist[index_to_remove]

        factory.forwarder.dispatch(PLAYLIST_EVENT_TRACK_REMOVED, track_id)

    def play_track(self, track_id):
        """ Play a track

        Keyword arguments:
        track_id -- Id of the track to play

        """

        index_of_track = self._find_index_of_track_id(track_id)

        track_to_play = self.playlist[index_of_track]

        if track_to_play is not None:
            # Request stream url from google music
            stream_url = self.mobileclient.get_stream_url(track_to_play["storeId"], self.deviceid)

            # Load stream url to mplayer
            self.player.loadfile(stream_url)

            # For some reason OSX needs to unpause mplayer
            if sys.platform == "darwin":
                self.player.pause()

            # Set track
            self.current_track_index = index_of_track

            # Cancel previous timer
            if self.timer is not None:
                self.timer.cancel()

            # How many minutes does the track last
            track_duration = long(track_to_play["durationMillis"]) / 1000

            # Set Timer to play next track when trackDuration is over
            self.timer = Timer(track_duration, self.play_next_track)
            self.timer.daemon = True
            self.timer.start()

            print "playing", track_to_play["artist"], " - ", track_to_play["title"], " : ", stream_url

            # Fire event that a new track is playing
            factory.forwarder.dispatch(TRACK_EVENT_PLAYBACK, json.dumps(track_to_play))

            return True
        else:
            return False

    def play_next_track(self):
        """ Play the next track in the playlist.

        Returns:
        True or False

        """

        if self.playtype == PlayType.LINEAR:
            # Index of next track to play
            next_track_index = self.current_track_index + 1

            # Restart at index 0 if end of playlist is reached
            if next_track_index >= len(self.playlist):
                next_track_index = 0

        elif self.playtype == PlayType.SHUFFLE:
            # Index of next track to play at random
            next_track_index = random.randrange(0, len(self.playlist), 1)

        # Obtain the id of the next track to play
        next_track_id = self.playlist[next_track_index]['id']

        # Play track with that id
        return self.play_track(next_track_id)

    def play_previous_track(self):
        """ Play the previous track in the playlist.

        Returns:
        True or False

        """

        if self.playtype == PlayType.LINEAR:
            # Index of previous track to play
            previous_track_index = self.current_track_index - 1

            # Contiune from the end of the playlist
            if previous_track_index <= 0:
                previous_track_index = len(self.playlist) - 1

        elif self.playtype == PlayType.SHUFFLE:
            # Index of the previous track is random
            previous_track_index = random.randrange(0, len(self.playlist), 1)

        # Obtain the id of the previous track to play
        previous_track_id = self.playlist[previous_track_index]['id']

        # Play track with that id
        return self.play_track(previous_track_id)

    def stop(self):
        """ Stop playback.

        """

        if self.timer is not None:
            self.timer.cancel()

        if self.player is not None:
            self.player.stop()

    def play(self):
        """ Start playing current track

        Returns:
        True if track has been started. Else False

        """
        current_track_id = self.playlist[self.current_track_index]
        return self.play_track(current_track_id)

    def _find_index_of_track_id(self, track_id):
        index = 0

        for track in self.playlist:
            if track['id'] == track_id:
                return index
            index += 1

        return None
Ejemplo n.º 17
0
class MediaPlayer(threading.Thread):

   def __init__(self, mqttbroker, settings):
      threading.Thread.__init__(self)
      self.settings = settings 
      self.player = False
      self.effect = False
      self.CurrentStation = ""
      self.CurrentStationNo = -1
      self.CurrentURL = ""
      self.stopping = False
      self.message = ""
      self.mqttbroker = mqttbroker
      self.increasingvolume = -1
      self.alarmThread = None
      self.playerrestarting = False

   def playerActive(self):
      # True if playing or mid restart
      return self.player!=False or self.playerrestarting

   def playerPaused(self):
      if self.player:
         return self.player.paused
      else:
         return True # not running actually!

   def playerActiveStation(self):
      if self.player:
          return self.CurrentStation
      else:
          return "None"

   def playerActiveStationNo(self):
      if self.player:
          return self.CurrentStationNo
      else:
          return -1

   def soundAlarm(self, alarmThread, Station = -1, StartVolume = -1):
      # STation = Station Number
      # StartVolume = Increasing volume from this level
      log.info("Playing alarm")
      self.alarmThread = alarmThread
      self.increasingvolume = StartVolume
      if (StartVolume != -1):
         self.settings.setVolume(StartVolume)
      self.playStation(Station)
      log.debug("Alarm process opened")

      # Wait a few seconds and see if the mplayer instance is still running
      time.sleep(self.settings.getInt('radio_delay'))

      if alarmThread.isSnoozing() or alarmThread.getNextAlarm() is None:
         # We've snoozed or cancelled the alarm, so no need to check for player
         log.debug("Media player senses alarm already cancelled/snoozed, so not checking for mplayer instance")
         return

      # Fetch the number of mplayer processes running
      processes = subprocess.Popen('ps aux | grep mplayer | egrep -v "grep" | wc -l',
         stdout=subprocess.PIPE,
         shell=True
      )
      num = int(processes.stdout.read())

      if num < 2 and self.player is not False:
         log.error("Could not find mplayer instance, playing panic alarm")
         self.stopPlayer()
         time.sleep(2)
         self.playMedia(PANIC_ALARM,0)


   def playStation(self,station=-1):
      if station==-1:
         station = self.settings.getInt('station')

      try:
         stationinfo = self.settings.getStationInfo(station)
      except:
         log.debug("invalid station no '%s'", str(station))
         stationinfo = None

      if (stationinfo != None):
         # Only change if its differant URL
         if (self.CurrentURL != stationinfo['url']):
            log.info("Playing station %s", stationinfo['name'])
            log.debug("Playing URL %s", stationinfo['url'])
            self.player = Player() # did have "-cache 2048"
            self.player.loadlist(stationinfo['url'])
            self.player.loop = 0
            self.CurrentStation = stationinfo['name']
            self.CurrentStationNo = station
            self.CurrentURL = stationinfo['url']
         else:
            log.info("Already Playing %s", stationinfo['name'])

         if (self.mqttbroker != None):
            self.mqttbroker.publish("radio/station",self.CurrentStation)
            self.mqttbroker.publish("radio/stationno",str(self.CurrentStationNo))
            self.mqttbroker.publish("radio/state","ON")
            self.mqttbroker.publish("radio/mute","OFF")

   def playStationURL(self,stationName, StationURL, StationNo = -1):

      log.info("Playing station %s", stationName)
      log.debug("Playing URL %s", StationURL)
      self.player = Player("-cache 320") # did have "-cache 2048"
      self.player.loadlist(StationURL)
      self.player.loop = 0
      self.CurrentStation = stationName
      self.CurrentStationNo = StationNo
      self.CurrentURL = StationURL
      if (self.mqttbroker != None):
         self.mqttbroker.publish("radio/station",self.CurrentStation)
         self.mqttbroker.publish("radio/stationno",str(StationNo))
         self.mqttbroker.publish("radio/state","ON")
         self.mqttbroker.publish("radio/mute","OFF")

   def playMedia(self,file,loop=-1):
      log.info("Playing file %s", file)
      self.player = Player()
      self.player.loadfile(file)
      self.player.loop = loop
      self.CurrentStation = file
      self.CurrentStationNo = -1
      self.CurrentURL = file
      if (self.mqttbroker != None):
         self.mqttbroker.publish("radio/station",self.CurrentStation)
         self.mqttbroker.publish("radio/stationno",str(self.CurrentStationNo))
         self.mqttbroker.publish("radio/state","ON")      
         self.mqttbroker.publish("radio/mute","OFF")

   # Play some speech. None-blocking equivalent of playSpeech, which also pays attention to sfx_enabled setting
   def playVoice(self,text):
      if (self.settings.get('sfx_enabled')==0) or (self.settings.getIntOrSet('quiet_reboot') == 1):
         # We've got sound effects disabled, so skip
         log.info("Sound effects disabled, not playing voice")
         return
      path = self.settings.get("tts_path");
      log.info("Playing voice: '%s' through `%s`" % (text,path))
      if path == "pico2wave":
        play = subprocess.Popen('pico2wave -l en-GB -w /tmp/texttosay.wav "%s" && aplay -q /tmp/texttosay.wav' % (text), shell=True)
      else:
        play = subprocess.Popen('echo "%s" | %s 2>/dev/null' % (text,path), shell=True)

   # Play some speech. Warning: Blocks until we're done speaking
   def playSpeech(self,text):
      if (self.settings.get('sfx_enabled')==0) or (self.settings.getIntOrSet('quiet_reboot') == 1):
         # We've got sound effects disabled, so skip
         log.info("Sound effects disabled, not playing voice")
         return
      path = self.settings.get("tts_path");
      log.info("Playing speech: '%s' through `%s`" % (text,path))
      if path == "pico2wave":
          play = subprocess.Popen('pico2wave -l en-GB -w /tmp/texttosay.wav "%s" && aplay -q /tmp/texttosay.wav' % (text), shell=True)
      else:
        play = subprocess.Popen('echo "%s" | %s  2>/dev/null' % (text,path), shell=True)

      play.wait()

   def stopPlayer(self):
      if self.player:
         self.player.quit()
         self.player = False
         self.CurrentURL = ""
         self.CurrentStationNo = -1
         self.CurrentStation = "N/A"
         log.info("Player process terminated")
         if (self.mqttbroker != None):
            self.mqttbroker.publish("radio/station",self.CurrentStation)
            self.mqttbroker.publish("radio/stationno",str(self.CurrentStationNo))
            self.mqttbroker.publish("radio/state","OFF")
            self.mqttbroker.publish("radio/mute","OFF")

   def pausePlayer(self):
      if self.player:
         self.player.pause()
         log.info("Player process paused/unpaused")
         if (self.mqttbroker != None):
            self.mqttbroker.publish("radio/state","ON")
            self.mqttbroker.publish("radio/mute","ON")
         return self.player.paused
      else:
         return True # not running actually!

   def restartPlayer(self):
      self.playerrestarting = True
      CurrentURL = self.CurrentURL
      CurrentStation = self.CurrentStation
      CurrentStationNo = self.CurrentStationNo
      log.info("Player Restarting")
      self.stopPlayer()
      time.sleep(2)
      self.playerrestarting = False
      self.playStationURL(CurrentStation, CurrentURL, CurrentStationNo)

   def publish(self):
        self.mqttbroker.publish("radio/volumepercent", self.settings.getInt("volumepercent"))
        self.mqttbroker.publish("radio/station",self.CurrentStation)
        self.mqttbroker.publish("radio/stationno",str(self.CurrentStationNo))
        if self.player:
            self.mqttbroker.publish("radio/state","ON")  
        else:
            self.mqttbroker.publish("radio/state","OFF")  

   def on_message(self, topic ,payload):
      method = topic[0:topic.find("/")] # before first "/"
      item = topic[topic.rfind("/")+1:]   # after last "/"
      log.debug("radio method='%s', item='%s'", method, item)
      done = False
      try:
         if (method == "radio"):
            if item == "state":
               if (payload.upper() == "ON"):
                  self.playStation(-1)
               elif (payload.upper() == "OFF"):
                  self.stopPlayer()
               else:
                  log.info("Invalid payload state '%s' [ON/OFF]", payload)
               done = True

            elif item == "stationno":
               try:
                  stationno = int(payload)
                  self.playStation(stationno)
               except ValueError:
                  log.warn("Could not decode %s as station no", payload)                        
               done = True

            elif (item == "volumepercent"):
               try:
                  self.settings.setVolume(int(payload))
               except ValueError:
                  log.warn("Could not decode %s as volume percent", payload)    
               done = True

      except Exception as e:
         log.debug("on_message Error: %s" , e)            
      return done

   def run(self):

      self.SleepTime = float(0.1)
      lastplayerpos = 1 # media player position
      NoneCount = 0
      checkmessage = 50
      lastmediatitle = ""

      if (self.mqttbroker != None):
         self.mqttbroker.set_radio(self) 
         self.publish()

      log.info("Player thread started")

      while(not self.stopping):
         time.sleep(self.SleepTime)

         try:

            checkmessage -= 1
            if (checkmessage <= 0):
               checkmessage = 25

               if self.playerActive(): # self.menu.backgroundRadioActive():
                  checkmessage = 10
                  try:
                     currentplayerpos = self.player.stream_pos
                     if (currentplayerpos > lastplayerpos) and (currentplayerpos != None):
                           self.message = ", Radio Playing"
                           NoneCount = 0
                     elif (currentplayerpos == None) or (lastplayerpos == -1):
                           log.info("last %s, current pos %s",lastplayerpos, currentplayerpos) #, self.media.player.stream_length)
                           self.message = ", Radio Buffering"
                           if (lastplayerpos == 0) and (currentplayerpos == None):
                               NoneCount += 1
                     else:
                           self.message = ", Radio Paused"
                           log.info("last %s, current pos %s ",lastplayerpos, currentplayerpos) #, self.media.player.stream_length)
                           if self.playerPaused() == False:
                              NoneCount += 1

                     lastplayerpos = currentplayerpos

                     try:
                        if lastmediatitle != (self.player.media_title):
                           log.info('media_title "%s" was "%s"', self.player.media_title, lastmediatitle)
                           lastmediatitle = str(self.player.media_title)
                     except:
                        #log.info("no media title")
                        lastmediatitle = ""

                     try:
                        metadata = self.player.metadata
                        for item in metadata:
                           log.info("metadata %s", item)
                     except:
                        #log.debug("no metadata, %s", metadata)
                        metadata = ""
                     try:
                        log.info("metadata %s", self.player.metadata[0])
                     except:
                        metadata = ""


                  except Exception as e: # stream not valid I guess
                     log.error("Error: %s" , e)
                     self.message = ", Radio Erroring"
                     NoneCount += 1
                     #~ lastplayerpos = currentplayerpos

                  if (NoneCount > 20): # or (currentplayerpos == None):
                        log.info("Player may be stuck, restarting")
                        NoneCount = 0
                        self.restartPlayer()

                  # DO we need to increase the volume?
                  if (self.increasingvolume != -1):

                     # if we have something to play increase volume
                     if currentplayerpos != None:
                           self.increasingvolume += 2
                           if self.increasingvolume >= self.alarmThread.alarmVolume: #settings.getInt('volume'):
                              #self.settings.setVolume(self.settings.getInt('volume'))
                              self.settings.setVolume(self.alarmThread.alarmVolume)
                              self.increasingvolume = -1 # At required volume
                              log.info("Reached alarm volume level")
                           else:
                              self.settings.setVolume(self.increasingvolume)

                  #try:
                  #   metadata = self.player.metadata or {}
                  #   log.info("Track %s", metadata.get('track', ''))
                  #   log.info("Comment %s", metadata.get('comment', ''))
                  #   log.info("artist %s", metadata.get('artist', ''))
                  #   log.info("album %s", metadata.get('album', ''))

                  #except Exception as e: # stream not valid I guess
                  #   log.error("metadata error: %s" , e)


               else:
                  self.message = ""

         except:
            log.exception("Error in Media loop")
            self.stopping = True
            self.message = ", Errored"
Ejemplo n.º 18
0
               else:
                  self.message = ""

         except:
            log.exception("Error in Media loop")
            self.stopping = True
            self.message = ", Errored"


if __name__ == '__main__':
    print ("Showing all current settings")
    media = MediaPlayer(None)
    print ("Playing file %s", PANIC_ALARM)
    player = Player("-cache 1024")
    player.loadfile(PANIC_ALARM)
    player.loop = 0
    # Set default prefix for all Player instances
    player.cmd_prefix = CmdPrefix.PAUSING_KEEP
    time.sleep(2)
    #~ try:

    meta = player.metadata['title']
    print ("title : " + meta)
    #~ except Exception as e:
        #~ e = sys.exc_info()[0]
        #~ print "Error: %s" % e
    time.sleep(2)
    player.stop()

Ejemplo n.º 19
0
class ZeroPlayer(Frame):
    def __init__(self, windowed=False):
        super().__init__()
        self.windowed = windowed
        self.user = getpass.getuser()
        if windowed:
            self.player = Player(args=('-xy', '800', '-geometry', '1100:100',
                                       '-noborder', '-ontop'))
        else:
            self.player = Player()
        self.mp3_search = "/media/" + self.user + "/*/*/*/*.mp*"
        self.m3u_def = "ALLTracks"
        self.m3u_dir = "/media/" + self.user + "/MUSIC/"
        self.mp4playing = False
        self.volume = 100
        self.stop_start = 22
        self.nexttrk = 27
        self.prevtrk = 23
        self.autoplay = 0
        self.track = ""
        self.track_no = 0
        self.drive_name = ""
        self.que_dir = self.m3u_dir + self.m3u_def + ".m3u"
        self.m = 0
        self.counter5 = 0
        self.trackchangetime = time.time() + GAPTIME
        self.status = IDLE
        self.cmdbutton = PLAYING
        self.play_stopped = False

        if RunningOnPi:
            print(alsaaudio.mixers())
            if len(alsaaudio.mixers()) > 0:
                for mixername in alsaaudio.mixers():
                    self.m = alsaaudio.Mixer(mixername)
            self.m.setvolume(self.volume)
            self.gpio_enable = 1
            GPIO.setmode(GPIO.BCM)
            GPIO.setwarnings(False)
            GPIO.setup(self.stop_start, GPIO.IN, pull_up_down=GPIO.PUD_UP)
            GPIO.setup(self.nexttrk, GPIO.IN, pull_up_down=GPIO.PUD_UP)
            GPIO.setup(self.prevtrk, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        # setup GUI
        self.canvas = tk.Canvas(width=320, height=240)
        self.canvas.bind("<Key>", self.key)
        self.canvas.bind("<Button-1>", self.callback)
        self.canvas.pack()
        self.bgimg = ImageTk.PhotoImage(
            Image.open('Minibackground.png').resize((320, 240),
                                                    Image.ANTIALIAS))
        self.canvas.create_image(0, 0, anchor=tk.NW, image=self.bgimg)
        self.titlefont = tkinter.font.Font(family='KG Defying Gravity Bounce',
                                           size=28)
        self.artistfont = tkinter.font.Font(family='Victoria', size=30)
        self.numberfont = tkinter.font.Font(family='DotMatrix', size=20)
        self.title_id = None
        self.artist_id = None
        self.remining_id = None
        self.start_id = None
        self.stop_id = None
        self.startimg = ImageTk.PhotoImage(
            Image.open('play.png').resize((32, 32), Image.ANTIALIAS))
        self.stopimg = ImageTk.PhotoImage(
            Image.open('stop.png').resize((32, 32), Image.ANTIALIAS))
        self.canvas.focus_set()
        self.change_start_button()

        self.length = 27

        if RunningOnPi:
            self.Check_switches()

        # check default .m3u exists, if not then make it
        if not os.path.exists(self.que_dir):
            self.Create_Playlist()
        self.init_tunes()
        self.Show_Track()

    def change_start_button(self):
        if self.status == PLAYING and self.cmdbutton == IDLE:
            if self.stop_id:
                self.canvas.delete(self.stop_id)
                self.stop_id = None
            self.start_id = self.canvas.create_image(20,
                                                     10,
                                                     anchor=tk.NW,
                                                     image=self.startimg)
            self.cmdbutton = PLAYING
        elif self.status == IDLE and self.cmdbutton == PLAYING:
            if self.start_id:
                self.canvas.delete(self.start_id)
                self.start_id = None
            self.stop_id = self.canvas.create_image(20,
                                                    10,
                                                    anchor=tk.NW,
                                                    image=self.stopimg)
            self.cmdbutton = IDLE

    def init_tunes(self):
        Tracks = []
        with open(self.que_dir, "r") as textobj:
            line = textobj.readline()
            while line:
                Tracks.append(line.strip())
                line = textobj.readline()
        self.tunes = []
        for counter in range(0, len(Tracks)):
            z, self.drive_name1, self.drive_name2, self.drive_name, self.artist_name, self.album_name, self.track_name = Tracks[
                counter].split('/')
            self.tunes.append(self.artist_name + "^" + self.album_name + "^" +
                              self.track_name + "^" + self.drive_name + "^" +
                              self.drive_name1 + "^" + self.drive_name2)

    def key(self, event):
        '''print("pressed", event.char)'''
        if event.char == 'w' and self.status == IDLE:
            self.Play()
        if event.char == 's' and self.status == PLAYING:
            self.Stop()
        if event.char == 'd':
            self.Next_Track()
        if event.char == 'a':
            self.Prev_Track()
        if event.char == 'q':
            quit()

    def callback(self, event):
        if time.time() < self.trackchangetime:
            return
        self.trackchangetime = time.time() + GAPTIME
        if event.y < 52:
            if self.status == PLAYING:
                print("clicked Stop", event.x, event.y)
                self.Stop()
            elif self.status == IDLE:
                print("clicked Play", event.x, event.y)
                self.Play()
        else:
            if event.x < 160:
                print("clicked Prev", event.x, event.y)
                self.Prev_Track()
            elif event.x > 160:
                print("clicked Next", event.x, event.y)
                self.Next_Track()

    def Check_switches(self):
        buttonPressed = False
        if GPIO.input(self.prevtrk) == 0:
            buttonPressed = True
            self.Prev_Track()
        elif GPIO.input(self.nexttrk) == 0:
            buttonPressed = True
            self.Next_Track()
        elif GPIO.input(self.stop_start) == 0:
            if self.status == PLAYING:
                buttonPressed = True
                self.Stop()
            elif self.status == IDLE:
                buttonPressed = True
                self.Play()
        if buttonPressed:
            self.after(200, self.Buttons_released)
        else:
            self.after(200, self.Check_switches)

    def Buttons_released(self):
        if self.status == IDLE:
            self.after(200, self.Check_switches)
            return
        buttonPressed = False
        if GPIO.input(self.prevtrk) == 0:
            buttonPressed = True
        elif GPIO.input(self.nexttrk) == 0:
            buttonPressed = True
        elif GPIO.input(self.stop_start) == 0:
            buttonPressed = True
        if buttonPressed:
            self.after(200, self.Buttons_released)
        else:
            self.after(200, self.Check_switches)

    def getline(self, str, breakpoint):
        if breakpoint is None:
            return str[0:TITLEHI] + ']\n[' + str[TITLEHI:]
        return str[0:breakpoint] + ']\n[' + str[breakpoint + 1:]

    def set_title(self, title):
        if self.title_id:
            self.canvas.delete(self.title_id)
        title_has_space = False
        title_has_lower = False
        for ch in title:
            if ch.islower():
                title_has_lower = True
            if ch == ' ' or ch == '_':
                title_has_space = True
        modded = ''
        breakpoints = []
        count = 0
        if title_has_lower == True and title_has_space == False:
            ''' Add spaces before every uppercase letter '''
            for ch in title:
                if ch.isupper():
                    if count == 0:
                        modded = modded + ch.lower()
                        count += 1
                    else:
                        modded = modded + '|' + ch.lower()
                        breakpoints.append(count)
                        count += 2
                if ch.islower():
                    modded = modded + ch
                    count += 1
        else:
            ''' Convert everything to lower case letters '''
            for ch in title:
                if ch.isupper():
                    modded = modded + ch.lower()
                    count += 1
                if ch.islower():
                    modded = modded + ch
                    count += 1
                if ch == ' ' or ch == '_':
                    modded = modded + '|'
                    breakpoints.append(count)
                    count += 1
        modded = '[' + modded + ']'
        goodbreak = 0
        extra = 0
        if len(modded) > TITLEHI:
            ''' Insert linebreak for first line '''
            goodbreak = 0
            extra = 1
            for b in breakpoints:
                if goodbreak == 0:
                    goodbreak = b
                if b > TITLELO and b < TITLEHI + 1:
                    goodbreak = b
            if goodbreak == 0:
                goodbreak = len(modded)
            elif len(modded) > goodbreak + extra:
                modded = self.getline(modded, goodbreak + extra)
                extra += 2
        if len(modded[goodbreak + extra:]) > TITLEHI:
            ''' Insert linebreaks for second line '''
            lastbreak = goodbreak
            for b in breakpoints:
                if b > lastbreak and goodbreak == lastbreak:
                    goodbreak = b
                if b > lastbreak and b - lastbreak > TITLELO and b - lastbreak < TITLEHI + 1:
                    goodbreak = b
            if len(modded) > goodbreak + extra:
                modded = self.getline(modded, goodbreak + extra)
        ''' Three lines is max for this display '''

        self.title_id = self.canvas.create_text(320 / 2,
                                                240 / 2 - 2,
                                                anchor='center',
                                                justify='center',
                                                text=modded,
                                                font=self.titlefont,
                                                fill='red')

    def set_artist(self, artist):
        if self.artist_id:
            self.canvas.delete(self.artist_id)
        self.artist_id = self.canvas.create_text(320 / 2,
                                                 210,
                                                 anchor='center',
                                                 text=artist,
                                                 font=self.artistfont)

    def set_remining_time(self, remining_time=None):
        if self.remining_id:
            self.canvas.delete(self.remining_id)
        if not remining_time is None:
            self.remining_id = self.canvas.create_text(310,
                                                       30,
                                                       anchor='e',
                                                       text=remining_time,
                                                       font=self.numberfont,
                                                       fill='light green')

    def tune(self):
        if 'mp4' in self.track:
            return 4000.0
        return 0.0

    def Show_Track(self):
        if len(self.tunes) > 0:
            self.artist_name,self.album_name,self.track_name,self.drive_name,self.drive_name1,self.drive_name2  = \
                self.tunes[self.track_no].split('^')
            self.track = os.path.join("/" + self.drive_name1, self.drive_name2,
                                      self.drive_name, self.artist_name,
                                      self.album_name, self.track_name)
            self.set_artist(self.artist_name)
            self.set_title(self.track_name[:-4])
            if os.path.exists(self.track):
                audio = MediaInfo.parse(self.track)
                self.track_len = (audio.tracks[0].duration +
                                  self.tune()) / 1000.0
                minutes = int(self.track_len // 60)
                seconds = int(self.track_len - (minutes * 60))

    def Play(self):
        self.autoplay = 1
        if self.status == IDLE:
            self.status = PLAYING
            self.Play_track()

    def Stop(self):
        self.status = IDLE
        self.autoplay = 0

    def Next_Track(self):
        if self.status == PLAYING:
            self.status = IDLE
            while self.play_stopped:
                time.sleep(0.2)
            self.inc_track()
        elif self.status == IDLE:
            self.inc_track()

    def Prev_Track(self):
        if self.status == PLAYING:
            self.status = IDLE
            while self.play_stopped:
                time.sleep(0.2)
            self.dec_track(2)
        elif self.status == IDLE:
            self.dec_track()

    def Play_track(self):
        if self.status == IDLE:
            return
        if os.path.exists(self.track):
            if 'mp3' in self.track or not RunningOnPi or UseOmxplayer == False:
                self.player.stop()
                if self.mp4playing:
                    os.killpg(self.p.pid, signal.SIGTERM)
                self.player.loadfile(self.track)
            else:
                self.player.stop()
                if self.mp4playing:
                    os.killpg(self.p.pid, signal.SIGTERM)
                if self.windowed:
                    rpistr = "omxplayer --win 800,90,1840,700 " + '"' + self.track + '"'
                else:
                    rpistr = "omxplayer --win 0,49,320,240 " + '"' + self.track + '"'
                self.p = subprocess.Popen(rpistr,
                                          shell=True,
                                          preexec_fn=os.setsid)
                self.mp4playing = True
            self.start = time.time()
        else:
            return
        self.play_stopped = False
        self.player.time_pos = 0
        self.show_remining_time()
        self.change_start_button()
        self.Play_track2()

    def Play_track2(self):
        if time.time() - self.start > self.track_len or self.status == IDLE:
            self.status = IDLE
            if self.mp4playing:
                os.killpg(self.p.pid, signal.SIGTERM)
                self.mp4playing = False
                self.player.stop()
            else:
                self.player.stop()
            self.show_remining_time()
            self.change_start_button()
            self.play_stopped = True
            if self.autoplay == 1:
                self.status = PLAYING
                self.inc_track()
            return
        self.show_remining_time()
        self.after(200, self.Play_track2)

    def show_remining_time(self):
        if self.status == IDLE:
            self.set_remining_time()
            return
        played = time.time() - self.start
        p_minutes = int(played // 60)
        p_seconds = int(played - (p_minutes * 60))
        lefttime = self.track_len - played
        minutes = int(lefttime // 60)
        seconds = int(lefttime - (minutes * 60))
        self.set_remining_time("%02d:%02d" % (minutes, seconds % 60))

    def inc_track(self):
        self.track_no += 1
        if self.track_no > len(self.tunes) - 1:
            self.track_no = 0
        self.Show_Track()
        if self.autoplay == 1:
            self.status = PLAYING
            self.Play_track()
        else:
            self.status = IDLE

    def dec_track(self, val=1):
        for i in range(0, val):
            self.track_no -= 1
            if self.track_no < 0:
                self.track_no = len(self.tunes) - 1
        self.Show_Track()
        if self.autoplay == 1:
            self.Play_track()
        else:
            self.status = IDLE

    def Create_Playlist(self):
        self.timer = time.time()
        if self.status == PLAYING:
            self.status = IDLE
            self.player.stop()
        if os.path.exists(self.m3u_dir + self.m3u_def + ".m3u"):
            os.remove(self.m3u_dir + self.m3u_def + ".m3u")
        self.Tracks = glob.glob(self.mp3_search)
        if len(self.Tracks) > 0:
            with open(self.m3u_dir + self.m3u_def + ".m3u", 'w') as f:
                for item in sorted(self.Tracks):
                    f.write("%s\n" % item)
Ejemplo n.º 20
0
class Video(object):
    def __init__(self, parent, name, texture, *args, **kwargs):

        self.video = False
        self.audio = False
        self.video_speed = 1.0
        self.video_time = 0
        self.video_loop = 0

        if isinstance(texture, str):
            match = videos_formats.match(texture.lower())
            if match and match.string:

                try:
                    global cv2, video_support
                    import cv2
                    video_support = True
                except:
                    LOGGER.error('python-opencv is required to play videos')

                if parent.audio:
                    try:
                        global Player, audio_support
                        from mplayer import Player, CmdPrefix
                        Player.cmd_prefix = CmdPrefix.PAUSING_KEEP
                        audio_support = True
                    except:
                        LOGGER.warning(
                            'mplayer.py not found, video will play without audio'
                        )

                if audio_support:

                    self.audio = True

                    audiopath = texture + '.wav'
                    if not os.path.isfile(audiopath):
                        print('extracting audio stream to ' + audiopath)
                        subprocess.run([
                            'ffmpeg', '-i', texture, '-acodec', 'pcm_s16le',
                            '-ac', '2', audiopath
                        ])

                    mplayer_args = ['-vo', 'null']

                    if parent.audio == 'jack':
                        jackname = parent.name + '/' + name
                        if len(jackname) > 63:
                            jackname = jackname[0:62]
                        mplayer_args.append('-ao')
                        mplayer_args.append('jack:name=%s' % jackname)

                    self.audio_reader = Player(args=mplayer_args)
                    self.audio_reader.loadfile(texture + '.wav')
                    self.audio_bypass = 0
                    self.set_audio_bypass(1)

                if video_support:

                    self.video = True

                    self.video_reader = cv2.VideoCapture(texture)
                    self.video_shape = (int(
                        self.video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT)),
                                        int(
                                            self.video_reader.get(
                                                cv2.CAP_PROP_FRAME_WIDTH)), 3)
                    self.video_blank_frame = numpy.zeros(self.video_shape,
                                                         dtype='uint8')
                    self.video_texture = pi3d.Texture(self.video_blank_frame,
                                                      mipmap=True)
                    self.frame_format = self.video_texture._get_format_from_array(
                        self.video_texture.image, self.video_texture.i_format)

                    self.video_frame_duration = 1. / min(
                        self.video_reader.get(cv2.CAP_PROP_FPS), 60)
                    self.video_duration = self.video_frame_duration * self.video_reader.get(
                        cv2.CAP_PROP_FRAME_COUNT)

                    self.video_elapsed_time = 0

                    texture = self.video_texture

        super(Video, self).__init__(parent=parent,
                                    name=name,
                                    texture=texture,
                                    *args,
                                    **kwargs)

        if self.video:
            self.active_effects.append('VIDEO')

    def draw(self, *args, **kwargs):

        if self.video and self.visible:
            self.video_next_frame()

        super(Video, self).draw(*args, **kwargs)

    @osc_property('video_time', 'video_time')
    def set_video_time(self, time):
        """
        current video time in seconds (cpu expensive for any value other than 0)
        """
        if not self.video:
            return

        time = float(time)

        if time > self.video_duration:
            time = 0
            if self.video_loop == 0:
                self.set_video_speed(0)
                self.video_load_frame(self.video_blank_frame)

        self.video_reader.set(cv2.CAP_PROP_POS_MSEC, time * 1000)
        self.video_time = time
        # self.video_reader.get(cv2.CAP_PROP_POS_MSEC) / 1000.

        if self.video_time > 0:
            self.video_elapsed_time = self.parent.time

        if self.audio:
            self.set_audio_sync()

    @osc_property('video_speed', 'video_speed')
    def set_video_speed(self, speed):
        """
        video playback speed (0=paused, no reverse playback, high speed is cpu expensive)
        """
        if not self.video:
            return

        self.video_speed = max(float(speed), 0)
        self.video_elapsed_time = 0

        if self.audio:
            if self.video_speed == 1:
                self.set_audio_sync()
                if self.visible:
                    self.set_audio_bypass(0)
            else:
                self.set_audio_bypass(1)

    @osc_property('video_loop', 'video_loop')
    def set_video_loop(self, loop):
        """
        video looping state (0|1)
            if not looping, video_speed will be set to 0 when the video reaches the last frame
        """
        self.video_loop = int(bool(loop))

    def video_next_frame(self):
        """
        Seek to current frame
        """

        time = self.parent.time

        if self.video_elapsed_time == 0 or self.video_speed == 0:
            self.video_elapsed_time = time
            if self.video_speed == 0:
                return

        delta = (time - self.video_elapsed_time)
        frames = int(delta / (self.video_frame_duration / self.video_speed))

        if frames > 0:

            for i in range(frames):

                ok = self.video_reader.grab()
                if not ok:
                    self.set_video_time(0)
                    if self.video_loop == 0:
                        self.set_video_speed(0)
                        self.video_load_frame(self.video_blank_frame)
                        return

            self.video_elapsed_time += frames * (self.video_frame_duration /
                                                 self.video_speed)

            self.video_time += frames * self.video_frame_duration
            # self.video_time = self.video_reader.get(cv2.CAP_PROP_POS_MSEC) / 1000.

            ok, frame = self.video_reader.retrieve()
            if ok:
                self.video_load_frame(frame)

    def video_load_frame(self, frame):
        """
        Load frame (numpy array) in texture
        """
        # return self.video_texture.update_ndarray(frame, 0)
        tex = self.video_texture
        opengles.glActiveTexture(GL_TEXTURE0)
        opengles.glBindTexture(GL_TEXTURE_2D, tex._tex)
        opengles.glTexSubImage2D(
            GL_TEXTURE_2D, 0, 0, 0, tex.ix, tex.iy, self.frame_format,
            GL_UNSIGNED_BYTE,
            frame.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte)))
        opengles.glGenerateMipmap(GL_TEXTURE_2D)

    def set_audio_bypass(self, state):
        """
        Internal: mute audio playback
        """
        state = int(bool(state))
        if self.audio_bypass != state:
            self.audio_bypass = state
            self.audio_reader.mute = bool(state)

    def set_audio_sync(self):
        """
        Sync audio at next frame
        """
        self.audio_reader.seek(self.video_time, 2)

    def property_changed(self, name):

        super(Video, self).property_changed(name)

        if self.audio:
            if name == 'visible' and self.video_speed == 1:
                if self.visible:
                    self.set_audio_sync()
                self.set_audio_bypass(self.visible == 0)
Ejemplo n.º 21
0
class BasePlayer(object):
    def __init__(self, playEndedCallback):
        self.isPlaying = False
        self.mplayer = MPlayer(autospawn=False)

        self.timer = Timer(interval=1, function=Player.loop, args=[self])
        self.timer.start()

        self.playEndedCallback = playEndedCallback


    def stop(self):
        self.isPlaying = False
        self.mplayer.stop()


    def pause_resume(self):
        self.mplayer.pause()


    def seek(self, amount):
        if self.mplayer.time_pos:
            self.mplayer.time_pos += amount


    def play(self, mediafile):
        self.isPlaying = True
        args = []
        self.mplayer.args = args
        self.mplayer.spawn()
        if mediafile:
            self.mplayer.loadfile(mediafile)
        


    def quit(self):
        self.isPlaying = False
        self.timer.cancel()
        self.mplayer.quit()
        print "timer cancelled"


    @classmethod
    def loop(cls, player):

        #return if not playing
        if not player.isPlaying: return

        t = Timer(1, cls.loop, [player])
        t.start()

        # from videotop import status_bar
        # status_bar.set_text("%s/%s -- curr: %s" % ( player.player.length, player.player.time_pos, player.current))

        # print("%s/%s -- curr: %s" % ( player.mplayer.length, player.mplayer.time_pos, player.current))
        if player.mplayer.length != None:
            time.sleep(1000)
        else:
            player.playEndedCallback()
            t.cancel()

    def __del__(self):
        self.quit()
Ejemplo n.º 22
0
class PiPlayBoxMode(BaseMode):
    def setup(self):
        self.modecolour = self.display.RED
        self.display.changeColour(self.modecolour)
        self.enabled = self.__ping()
        self.mplayer = None

        if self.enabled:

            self.actions = {
                0: {
                    "text": "Capital FM",
                    "sound": "http://ice-sov.musicradio.com:80/CapitalMP3"
                },
                1: {
                    "text": None,
                    "sound": None
                },
                2: {
                    "text": None,
                    "sound": None
                },
                3: {
                    "text": None,
                    "sound": None
                },
                4: {
                    "text": None,
                    "sound": None
                },
                5: {
                    "text": None,
                    "sound": None
                },
                6: {
                    "text": None,
                    "sound": None
                },
                7: {
                    "text": None,
                    "sound": None
                }
            }
            self.addInterrupts()
            self.modename = "Internet Radio"
            self.subtext = "ONLINE"
            self.mplayer = Player()

        else:

            self.modename = "No Internet"
            self.subtext = "Connection"

        self.display.Update("%s\n%s" % (self.modename, self.subtext))

    def __ping(self):
        self.display.Update("Checking if\nonline...")
        try:
            a = check_call(
                ["/bin/ping", "www.bbc.co.uk", "-c", "1", "-t", "200"])
            return True
        except CalledProcessError:
            return False

    def addInterrupts(self):

        e = GPIO.add_event_detect
        for i in range(8):
            e(self.buttons[i],
              GPIO.RISING,
              lambda channel, x=i: self.buttonAction(x),
              bouncetime=600)

    def buttonAction(self, button):
        action = self.actions[button]
        if action["text"] is not None:

            self.display.Update(action["text"])
            self.mplayer.stop()
            self.speaker.Unmute()
            self.mplayer.loadfile(action["sound"])

    def quit(self):
        if self.mplayer is not None and self.mplayer.is_alive():
            self.mplayer.stop()
            self.mplayer.quit()
            self.speaker.Mute()
            self.mplayer = None
Ejemplo n.º 23
0
class UbuntuDJ:
    def __init__(self, parent, mplayerloc, hideonplay, showonstop, controls):

        self.parent = parent
        self.hideonplay = hideonplay
        self.showonstop = showonstop
        self.controls = controls
        self.parent.title('UbuntuDJ')

        # initially visible and not playing
        self.visible = True
        self.playing = False
        self.selected = 0

        # get mplayer info
        Player.exec_path = mplayerloc
        Player.introspect()
        self.p = Player()

        # bottom labels
        self.songname = StringVar()
        self.label1 = Label(parent, textvariable=self.songname, anchor=W)
        self.label1.pack(side=BOTTOM)
        self.status = StringVar()
        self.label2 = Label(parent, textvariable=self.status)
        self.label2.pack(side=BOTTOM)

        # scrollbar and listbox
        self.scrollbar = Scrollbar(parent)
        self.scrollbar.pack(side=LEFT, fill=Y)

        self.listbox = Listbox(parent, yscrollcommand=self.scrollbar.set, selectmode=BROWSE)
        for i in directorymap:
            self.listbox.insert(END, i)
        self.listbox.pack(side=LEFT, fill=BOTH, expand=1)

        self.scrollbar.config(command=self.listbox.yview)

        # select first item
        self.listbox.focus_set()
        self.listbox.selection_set(0)

        # bind to click too
        self.listbox.bind('<<ListboxSelect>>', self.OnClick)

        # topmost window
        self.parent.wm_attributes("-topmost", 1)

        # set up labels
        self.UpdateLabels()

    def ButtonPress(self, button):
        if button == self.controls['playstop']:     # play/stop
            self.PlayStop()
        elif button == self.controls['navup']:      # nav up
            if self.selected != 0:
                self.listbox.selection_clear(self.selected)
                self.selected -= 1
                self.listbox.selection_set(self.selected)
                self.listbox.activate(self.selected)
                self.listbox.see(self.selected)
        elif button == self.controls['navdown']:    # nav down
            if self.selected != self.listbox.size()-1:
                self.listbox.selection_clear(self.selected)
                self.selected += 1
                self.listbox.selection_set(self.selected)
                self.listbox.activate(self.selected)
                self.listbox.see(self.selected)
        elif button == self.controls['volup']:      # vol inc
            self.p.volume = Step(1)
            self.UpdateLabels()
        elif button == self.controls['voldown']:    # vol dec
            self.p.volume = Step(-1)
            self.UpdateLabels()
        elif button == self.controls['showhide']:   # show/hide
            self.ShowHide()
        elif button == self.controls['reset']:      # reset
            self.Reset()
        elif button == self.controls['quit']:       # exit
            self.Reset()
            self.parent.quit()

    def PlayStop(self):

        self.listbox.focus_set()
        if self.playing:
            self.playing = False
            self.p.quit()           # quit and get new player
            self.p = Player()
            if self.showonstop:
                self.parent.update()
                self.parent.deiconify()
                self.visible = True
            self.UpdateLabels()
        else:
            self.playing = True
            song = self.listbox.get(ACTIVE)
            prefix = directorymap[song]
            self.p.loadfile(prefix+'/'+song)
            if self.hideonplay:
                self.parent.withdraw()
                self.visible = False
            self.UpdateLabels()

    def ShowHide(self):
        if self.visible:
            self.parent.withdraw()
            self.visible = False
        else:
            self.parent.update()
            self.parent.deiconify()
            self.visible = True

    def OnClick(self, event):
        w = event.widget
        index = int(w.curselection()[0])
        self.selected = index
        self.listbox.activate(index)

    def UpdateLabels(self):
        playing = ('Playing' if self.playing else 'Stopped')
        volume = ('None' if self.p.volume is None else str(self.p.volume))
        self.status.set(playing + ' | Volume: ' + volume)
        songname = (self.listbox.get(ACTIVE) if self.playing else '-')
        self.songname.set(songname)

    def Reset(self):
        self.p.quit()
        self.p = Player()
        self.playing = False
        self.UpdateLabels()
Ejemplo n.º 24
0
class MediaPlayer:

   def __init__(self):
      self.settings = Settings.Settings()
      self.player = False
      self.effect = False

   def playerActive(self):
      return self.player!=False

   def soundAlarm(self, alarmThread):
      log.info("Playing alarm")
      self.playStation()
      log.debug("Alarm process opened")

      # Wait a few seconds and see if the mplayer instance is still running
      time.sleep(self.settings.getInt('radio_delay'))

      if alarmThread.isSnoozing() or alarmThread.getNextAlarm() is None:
         # We've snoozed or cancelled the alarm, so no need to check for player
         log.debug("Media player senses alarm already cancelled/snoozed, so not checking for mplayer instance")
         return

      # Fetch the number of mplayer processes running
      processes = subprocess.Popen('ps aux | grep mplayer | egrep -v "grep" | wc -l',
         stdout=subprocess.PIPE,
         shell=True
      )
      num = int(processes.stdout.read())

      if num < 2 and self.player is not False:
         log.error("Could not find mplayer instance, playing panic alarm")
         self.stopPlayer()
         time.sleep(2)
         self.playMedia(PANIC_ALARM,0)

   def playStation(self,station=-1):
      if station==-1:
         station = self.settings.getInt('station')

      station = Settings.STATIONS[station]

      log.info("Playing station %s", station['name'])
      self.player = Player()
      self.player.loadlist(station['url'])
      self.player.loop = 0

   def playMedia(self,file,loop=-1):
      log.info("Playing file %s", file)
      self.player = Player()
      self.player.loadfile(file)
      self.player.loop = loop

   # Play some speech. None-blocking equivalent of playSpeech, which also pays attention to sfx_enabled setting
   def playVoice(self,text): 
      if self.settings.get('sfx_enabled')==0:
         # We've got sound effects disabled, so skip
         log.info("Sound effects disabled, not playing voice")
         return
      log.info("Playing voice: '%s'" % (text))
      play = subprocess.Popen('/usr/bin/espeak "%s" >& /dev/null' % (text), shell=True)

   # Play some speech. Warning: Blocks until we're done speaking
   def playSpeech(self,text):
      log.info("Playing speech: '%s'" % (text))
      play = subprocess.Popen('/usr/bin/espeak "%s" >& /dev/null' % (text), shell=True)
      play.wait()

   def stopPlayer(self):
      if self.player:
         self.player.quit()
         self.player = False
         log.info("Player process terminated")
Ejemplo n.º 25
0
class MediaPlayer:
    def __init__(self, settings):
        self.settings = settings
        self.player = False
        self.effect = False
        self.spotify = None

        self.alarm_media = settings.get("alarm_media")

        if self.alarm_media == 'Spotify':
            log.debug("Loading Spotify")
            self.spotify = SpotifyThread.SpotifyThread(settings)
            self.spotify.setDaemon(True)
            self.spotify.start()
        #     #self.spotify.setDaemon(True)
        #     # log.debug("Spotify event loop")
        #     # self.spotify.event_loop = self.spotify.EventLoop(self.session)
        #     # self.spotify.event_loop.start()
        #     #self.spotify.login(settings.get("spotify_user"), settings.get("spotify_pass"))

    def playerActive(self):
        # log.debug("playerActive: {0}".format(self.player != False))
        if self.alarm_media == 'Spotify':
            if self.spotify.spotify.session.player.state == "playing":
                return True
            else:
                return False

        else:
            if self.player != False:
                return True
            else:
                return False
        # return self.player != False

    def soundAlarm(self, snoozing=False):
        log.info("soundAlarm: Playing alarm")

        if self.alarm_media == 'Spotify':
            self.playSpotify(snoozing)
        else:
            self.playStation()

            log.debug("Verifying Radio is playing")
            # Wait a few seconds and see if the mplayer instance is still running
            time.sleep(self.settings.getInt('radio_delay'))

            # Fetch the number of mplayer processes running
            processes = subprocess.Popen(
                'ps aux | grep mplayer | egrep -v "grep" | wc -l',
                stdout=subprocess.PIPE,
                shell=True)
            num = int(processes.stdout.read())

            if num < 2 and self.player is not False:
                log.error(
                    "Radio fail: Could not find mplayer instance, playing panic alarm"
                )
                self.stopPlayer()
                time.sleep(2)
                self.playMedia(PANIC_ALARM, 0)
            else:
                log.debug("Radio success")

    def playSpotify(self, snoozing=False):
        log.debug("playSpotify: ")
        #self.spotify = SpotifyThread()
        if snoozing:
            log.debug("resuming")
            self.spotify.resume()
        else:
            log.debug("play")
            #play_thread = self.spotify.play()
            #play_thread.join()
            self.spotify.play()
        log.debug("leaving playSpotify: ")

    def playStation(self):
        log.debug("playStation: ")
        station = self.settings.get('station')

        log.info("Playing station %s", station)
        self.player = Player()
        self.player.loadlist(station)
        self.player.loop = 0

    def playMedia(self, file, loop=-1):
        log.info("playMedia: Playing file %s", file)
        self.player = Player()
        self.player.loadfile(file)
        self.player.loop = loop

    # Play some speech. None-blocking equivalent of playSpeech, which also pays attention to sfx_enabled setting
    def playVoice(self, text):
        log.debug("playVoice (non-blocking): {0}".format(text))
        if self.settings.get('sfx_enabled') == 0:
            # We've got sound effects disabled, so skip
            log.info("Sound effects disabled, not playing voice")
            return
        log.info("Playing voice: '%s'" % (text))
        play = subprocess.Popen('../speech/googletts "%s"' % (text),
                                shell=True)

    # Play some speech. Warning: Blocks until we're done speaking
    def playSpeech(self, text):
        log.debug("playSpeech (blocking): {0}".format(text))
        if self.settings.get('sfx_enabled') == 0:
            log.info("Playing speech: '%s'" % (text))
            play = subprocess.Popen('../speech/googletts "%s"' % (text),
                                    shell=True)
            play.wait()

    def stopPlayer(self):
        log.debug("stopPlayer: ")
        if self.player:
            self.player.quit()
            self.player = False
            log.info("Player process terminated")
Ejemplo n.º 26
0
while 1:
 x = ser.readline()
 vals = x.strip().split(',')
 print " "
 print old_vals
 print vals
 for i in range(0, len(vals)):
  if (int(vals[i]) == 1 and int(old_vals[i]) == 0):
   print "trigger " + str(i)
   if (i == 7):
    if (random.randint(0,1) == 0 or just_changed_palette == 1):
     just_changed_palette = 0
     playerv.stop()
     vid = video_file(random.randint(1,total_video_files))
     print vid
     playerv.loadfile(vid)
     playerv.fullscreen = True
    else:
     playerv.stop()
     playerv.loadfile(long_file(random.randint(1,total_long_files)))
     playerv.fullscreen = True
   elif (i == 8):
    palette_counter = palette_counter + 1
    palette = palette_counter % total_palettes
    just_changed_palette = 1
    print "counter is at " + str(palette_counter)
    print "palette is at " + str(palette)
   else:
    print sound_file(palette,idx[i])
    os.system(play_cmd(sound_file(palette,idx[i])))
 old_vals = vals
Ejemplo n.º 27
0
from mplayer import Player, CommandPrefix

#import mplayer
# Set default prefix for all Player instances
Player.cmd_prefix = CommandPrefix.PAUSING_KEEP
#print(path)

#Player.path ="/usr/bin/mplayer"

#Since autospawn is True by default, no need to call player.spawn() manually
player = Player()

# Play a file
#player.loadfile('http://retransmisorasenelpais.cienradios.com.ar:8000/la100.aac')
player.loadfile('audio.mp3')

# Pause playback
#player.pause()

# Get title from metadata
##metadata = player.metadata or {}
##print metadata.get('Title', '')

# Print the filename
##print player.filename

# Seek +5 seconds
##player.time_pos += 5

# Set to fullscreen
##player.fullscreen = True
Ejemplo n.º 28
0
                    sleep(0.4)
                    lcd.message("Mensagem\nrecebida!")
                    sleep(0.4)
                    lcd.clear()
                    sleep(0.4)
                    
                    texto = tirar_acentos(texto)
                    lcd.message(texto[:16])
                    sleep(0.5)
                    for i in range(len(texto)-15):
                        lcd.clear()
                        lcd.message(texto[i:16+i])
                        sleep(0.2)
                    sleep(2)
                    lcd.clear()
            elif ("voice" in mensagem):
                id_do_arquivo = mensagem["voice"]["file_id"]
                dados = {"file_id": id_do_arquivo}
                resposta = get(endereco_get_file, json=dados)
                dicionario = resposta.json()
                final_do_link = dicionario["result"]["file_path"]
                link_do_arquivo = "https://api.telegram.org/file/bot" + chave + "/" + final_do_link
                arquivo_de_destino = "audio-chat.ogg"
                urlretrieve(link_do_arquivo, arquivo_de_destino)
                player.loadfile(arquivo_destino)
        
        if result != []:
            ultimo_id = result[-1]['update_id']


Ejemplo n.º 29
0
class MPlayer(QObject):
    stateChanged = pyqtSignal(int)

    def __init__(self, xid, *args, **kwargs):
        QObject.__init__(self, *args, **kwargs)
        self.mp = Player(args=('-wid', str(int(xid)), '-vf', 'eq2',
                               '-fixed-vo', '-af', 'volume', '-volume', '0',
                               '-cache', '512'))
        self.url = None
        self.player_state = PLAYERSTATE_STOPPED
        self.check_state = False

    def play(self, url):
        if self.url == url:
            return
        self.url = url
        if not self.check_state:
            self.check_state = True
            threading.Thread(target=self._monitor_state).start()
        self.mp.loadfile(self.url)

    def _monitor_state(self):
        while self.mp.filename is None:
            time.sleep(1)
        self.mp.pause()
        while self.check_state:
            state = PLAYERSTATE_STOPPED
            if self.mp is None:
                state = PLAYERSTATE_STOPPED
            if self.mp.filename is None:
                state = PLAYERSTATE_STOPPED
            if self.mp.paused:
                state = PLAYERSTATE_PAUSED
            if self.mp.filename and not self.mp.paused:
                state = PLAYERSTATE_PLAYING
            if state != self.player_state:
                self.player_state = state
                self.stateChanged.emit(state)
                return
            time.sleep(0.1)
        self.player_state = PLAYERSTATE_STOPPED

    def pause(self):
        if self.mp:
            self.mp.pause()
            if self.player_state == PLAYERSTATE_PAUSED:
                self.player_state = PLAYERSTATE_PLAYING
            else:
                self.player_state = PLAYERSTATE_PAUSED
            self.stateChanged.emit(self.player_state)

    def unpause(self):
        self.pause()

    def stop(self):
        if self.mp:
            self.mp.stop()
            self.stateChanged.emit(PLAYERSTATE_STOPPED)
        self.check_state = False
        self.url = None

    def setVolume(self, value):
        if self.mp:
            self.mp.volume = value

    def setEq(self, b, c, s, h):
        if self.mp:
            self.mp.brightness = b
            self.mp.contrast = c
            self.mp.saturation = s
            self.mp.hue = h

    def setRatio(self, ratio):
        if not self.mp:
            return
        if ratio == 0:
            ratio = 0
        elif ratio == 1:
            ratio = 1
        elif ratio == 2:
            ratio = 1.5
        elif ratio == 3:
            ratio = 1.33
        elif ratio == 4:
            ratio = 1.25
        elif ratio == 5:
            ratio = 1.55
        elif ratio == 64:
            ratio = 1.4
        elif ratio == 7:
            ratio = 1.77
        elif ratio == 8:
            ratio = 1.6
        elif ratio == 9:
            ratio = 2.35
        self.mp.switch_ratio(ratio)

    def state(self):
        # print("state: {0}".format(self.player_state))
        return self.player_state