Example #1
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 __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
Example #3
0
def queue_daemon(app):
    mp = Player()
    while 1:
        msg = redis.blpop(app.config["REDIS_QUEUE_KEY"])
        # path = loads(msg[1])
        # print path
        # mp._run_command('loadfile "%s" 1\n' % path)
        mp._run_command(loads(msg[1]))
Example #4
0
    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
Example #5
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
Example #6
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
Example #7
0
    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))
Example #8
0
 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")
Example #9
0
    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()
Example #10
0
   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")
Example #11
0
    def __init__(self, args):
        def dict2args(a):
            return ["-{}={}".format(k, v) for k, v in a.items()]

        base_args = ('-slave', '-idle', '-really-quiet', '-msglevel',
                     'global=4', '-noconfig', 'all')
        super().__init__(Player(args=dict2args(args) + base_args))
Example #12
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
Example #13
0
    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
Example #14
0
    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
Example #15
0
 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
Example #16
0
 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()
Example #17
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
Example #18
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
Example #19
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")
Example #20
0
def playTheme(fileName):
	output('speaker',1)
	player = Player()
	player.loadfile(fileName)
	# Terminate MPlayer
	player.quit()	
	output('speaker',0)
Example #21
0
    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__()
Example #22
0
    def __init__(self, subsonic, msg_queue):
        self.config = read_config()
        self.cache_dir = os.path.join(
            self.config["sonar"]["sonar_dir"],
            "cache"
        )

        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__()
Example #23
0
class Mp3Player():
	
	def __init__(self):
		Player.exec_path = '/usr/bin/mplayer'
		Player.introspect()
		self.p = Player()
		
	def playAlbum(self, filename):
		self.p.loadlist(filename)
		
	def pause(self):
		self.p.pause()
		
	def previous(self):
		#TODO on press allway the previous track is playerd. normaly the first press goes back
		#to the start of the current track
		# -- to archive this we should first read the current positon .. is it is > XX sec we seek to 0 if below we go to previous track
		self.p.pt_step(-1)
		
	def next(self):
		self.p.pt_step(1)
Example #24
0
    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()
Example #25
0
    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()
Example #26
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
Example #27
0
	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)
Example #28
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
Example #29
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()
Example #30
0
 
def video_file(i):
  return 'clips/using-videos/' + str(i) + '.mp4'

def button_idx(button_order):
  idx = range(0,max(button_order)+1)
  for i in range(0,len(button_order)):
    idx[button_order[i]] = i
  return idx

def play_cmd(MEDIA):
  return 'mplayer ' + shellquote(MEDIA) + ' &>/dev/null </dev/null &'


idx = button_idx(button_order)
playerv=Player() #Player module only used for videos
ser = serial.Serial('/dev/ttyACM0',9600)
ser.readline() # toss one line so we are aligned
old_vals = vals = ['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0']
palette = palette_counter = 0
just_changed_palette = 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):
Example #31
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()
Example #32
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")
Example #33
0
 def playMedia(self,file,loop=-1):
    log.info("Playing file %s", file)
    self.player = Player()
    self.player.loadfile(file)
    self.player.loop = loop
Example #34
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")
Example #35
0
 def playMedia(self, file, loop=-1):
     log.info("Playing file %s", file)
     self.player = Player()
     self.player.loadfile(file)
     self.player.loop = loop
Example #36
0
    if (player.time_pos < 2):
        player.pt_step(-1)
    else:
        player.time_pos = 0


def exibirFaixa():
    metadados = player.metadata
    if (metadados):
        faixa = player.metadata["Title"]
        lcd.clear()
        lcd.message(faixa)


# criação de componentes
player = Player()
player.volume = 30
player.loadlist("playlist.txt")
player.volume = 30
botao1 = Button(11)
botao2 = Button(12)
botao3 = Button(13)
led1 = LED(21)
led3 = LED(23)
lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2)

player.pause()
led1.blink()

botao2.when_pressed = tocarPausarMusica
botao3.when_pressed = proxFaixa
Example #37
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
Example #38
0
def Entrou():
    global tempo
    tempo = datetime.now()


def Saiu():
    intervalo = datetime.now() - tempo
    if (intervalo.seconds >= 10):
        SendText("Pessoa saiu")


# criação de componentes
tempo = datetime.now()
sensor = DistanceSensor(trigger=17, echo=18)
sensor.threshold_distance = 0.1
player = Player()
aplicativo = None
but1 = Button(11)
but2 = Button(12)
but3 = Button(13)
led1 = LED(21)
buz = Buzzer(16)

but1.when_released = buttonReleased
but1.when_pressed = buttonPressed
but2.when_pressed = closeDoor
but3.when_pressed = Gravacao
but3.when_released = parar_gravacao
sensor.when_in_range = Entrou
sensor.when_out_of_range = Saiu
lastUpdate = 0
        fim = 16;

def gerarPlaylist():
    file = open("playlist.txt", "r")
    newPlaylist = file.read().split("\n")
    random.shuffle(newPlaylist)
    newFile = open("novaPlaylist.txt", "w")
    for musica in newPlaylist:
        if(len(musica) > 0):
            newFile.write(musica + "\n")
			
	file.close();
	newFile.close();

# criação de componentes
player = Player();
player.volume = 30;
gerarPlaylist();
player.loadlist("novaPlaylist.txt");
player.volume = 30;
botao1 = Button(11);
botao2 = Button(12);
botao3 = Button(13);
led1 = LED(21);
led3 = LED(23);
lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2);

player.pause()
led1.blink()

botao2.when_pressed = tocarPausarMusica;
def programa():

    # importação de bibliotecas
    import random
    import numpy as np
    from time import sleep
    from mplayer import Player
    from gpiozero import LED
    from gpiozero import Button
    from Adafruit_CharLCD import Adafruit_CharLCD

    # definição de funções
    #player.loadfile("musica.mp3")
    #player.loadlist("lista.txt")

    def TocarEPausar():
        player.pause()
        if (player.paused):
            led.blink()
        else:
            led.on()

    def ProximaFaixa():
        player.pt_step(1)
        #player.speed = 2
        return

    def FaixaAnterior():
        if (player.time_pos > 2.00):
            player.time_pos = 0.00
            return
        player.pt_step(-1)
        return

    def Acelera():
        player.speed = player.speed * 2

    def VoltaAoNormal():
        velocidade = player.speed
        if velocidade != None and velocidade > 1:
            player.speed = 1
            return
        ProximaFaixa()

    def embaralhaLista():

        f = open("playlist.txt", "r")
        lista = f.readlines()
        random.shuffle(lista)
        f.close()

        f = open("playlist_nova.txt", "w")
        f.writelines(lista)
        f.close()

        player.loadlist("playlist_nova.txt")
        #lista = random.shuffle("playlist.txt")
        #player.loadlist(lista)
        ###
        #arr = np.array(lista)
        #test =np.loadtxt(lista)
        #test =np.loadtxt("playlist.txt")
        #test= np.random.shuffle(test)
        #np.savetxt("listanova.txt",test)

        #print(test)

    # criação de componentes

    player = Player()
    player.loadlist("playlist.txt")

    led = LED(21)

    lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2)

    button1 = Button(11)
    button2 = Button(12)
    button3 = Button(13)
    button4 = Button(14)

    button1.when_pressed = FaixaAnterior

    button2.when_pressed = TocarEPausar

    button3.when_held = Acelera

    button3.when_released = VoltaAoNormal
    button4.when_pressed = embaralhaLista

    led.on()
    # loop infinito
    while True:
        metadados = player.metadata
        posicao = player.time_pos
        duracao = player.length

        if (metadados != None and posicao != None and duracao != None):
            nome = metadados["Title"]
            #if string.count(nome)>16:

            tempo_atual = int(posicao)
            tamanho = int(duracao)

            minuto_atual = str(tempo_atual // 60)
            segundos_atual = str(int(tempo_atual % 60))

            tamanho_minutos = str(tamanho // 60)
            tamanho_segundos = str(int(tamanho % 60))

            texto = "%s:%s de %s:%s" % (
                minuto_atual.zfill(2), segundos_atual.zfill(2),
                tamanho_minutos.zfill(2), tamanho_segundos.zfill(2))

            lcd.clear()
            lcd.message(nome)
            lcd.message('\n')
            lcd.message(texto)

        sleep(0.2)
Example #41
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.contrib.cache import SimpleCache
from mplayer import Player, CmdPrefix
from consoles import Console

app = Flask(__name__)
app.config.from_object('config')
cache = SimpleCache()
cache.default_timeout = 86400
player = Player()
metaplayer = Player(args=('-af','volume=-200:1'))
metaplayer.cmd_prefix = CmdPrefix.PAUSING
db = SQLAlchemy(app)
console = Console()
sleeper = None

import views, sockets, models, music, context_processors



Example #42
0
 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)
Example #43
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()
Example #44
0
import glob
from pymediainfo import MediaInfo
from PIL import ImageTk, Image
from mplayer import Player
import tkinter.font
import math
import getpass

RunningOnPi = os.uname()[4].startswith('arm')
UseOmxplayer = False
if RunningOnPi:
    import RPi.GPIO as GPIO
    import alsaaudio
    UseOmxplayer = True

Player.introspect()
global fullscreen
fullscreen = 0

TITLELO = 4
TITLEHI = 12

IDLE = 0
PLAYING = 1

GAPTIME = 0.2


class ZeroPlayer(Frame):
    def __init__(self, windowed=False):
        super().__init__()
def Passa():
    if player.speed == 1:
        player.pt_step(1)
    else:
        player.speed = 1


def Recua():
    if player.time_pos > 2:
        player.time_pos = 0
    else:
        player.pt_step(-1)


# criação de componentes
player = Player()
player.loadlist("playlist.txt")

b1 = Button(11)
b1.when_pressed = Recua
b2 = Button(12)
b2.when_pressed = Play
b3 = Button(13)
b3.when_held = Avança
b3.when_released = Passa
led1 = LED(21)
led3 = LED(23)
led3.off()
led1.on()
lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2)
pos = player.time_pos
Example #46
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)
Example #47
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()
Example #48
0
    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()
Example #49
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()
Example #50
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)
Example #51
0
 def __init__(self, *args, **kwargs):
     self.argparser = None
     self.exit = False
     self.paused = False
     self.player = Player()
Example #52
0
    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')
Example #53
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()
Example #54
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
Example #55
0
    if (datetime.now() - horaChegada >= timedelta(seconds=10)):
        dados = {"chat_id": id_da_conversa, "text": "Pessoa saiu!"}
        resposta = post(endereco_mensagem, json=dados)
    

# criação de componentes
botao1 = Button(11)
botao2 = Button(12)
botao3 = Button(13)
buzzer = Buzzer(16)

led1 = LED(21)

lcd = LCD(2, 3, 4, 5, 6, 7, 16, 2)

player = Player()

sensor = DistanceSensor(trigger=17, echo=18)
sensor.threshold_distance = 0.2

botao1.when_pressed = ligar_campainha
botao1.when_released = enviar_mensagem

botao2.when_pressed = led1.off

botao3.when_pressed = iniciar_gravacao
botao3.when_released = parar_gravacao

sensor.when_in_range = pessoa_porta
sensor.when_out_of_range = pessoa_saiu
Example #56
0
 def Reset(self):
     self.p.quit()
     self.p = Player()
     self.playing = False
     self.UpdateLabels()
Example #57
0
print("""

Touch pHAT: Buttons Demo & mplayer bluetooth
rely on linux mplayer -> alsa -> bluealsa a2dp source -> bluetooth for audio
rely on gPodder for podcast management
intially designed for Raspberry Pi Zero W 1.1 + Raspbian Buster Lite

Lights up each LED in turn, then detects your button presses.

Press Ctrl+C to exit!

""")
''' access to mplayer '''
out = open(str(Path.home()) + "/mplayer.log", "a")
err = open(str(Path.home()) + "/mplayer.err.log", "a")
p = Player(stdout=out, stderr=err)

# Check availability of touch pHat
has_pHat = True
try:
    import touchphat
except ImportError:
    print(
        "touch pHat not available, keyboard interface only (requires X session)"
    )
    has_pHat = False

# import for keyboard if available (usually through ssh -X or for dev)
has_keyboard = True
try:
    from pynput import keyboard
Example #58
-1
def programa():
    
    # importação de bibliotecas
    from time import sleep
    from mplayer import Player
    from gpiozero import LED
    from gpiozero import Button
    from Adafruit_CharLCD import Adafruit_CharLCD


    # definição de funções
    #player.loadfile("musica.mp3")
    #player.loadlist("lista.txt")

    def TocarEPausar():
      player.pause()
      if (player.paused):
        led.blink()
      else:
        led.on()


    def ProximaFaixa():
      player.pt_step(1)
      return

    def FaixaAnterior():
      if (player.time_pos > 2.00):
        player.time_pos = 0.00
        return
      player.pt_step(-1)
      return

    # criação de componentes
    player = Player()
    player.loadlist("playlist.txt")

    led = LED(21)
    
    lcd = Adafruit_CharLCD(2,3,4,5,6,7,16,2)

    button1 = Button(11)
    button2 = Button(12)
    button3 = Button(13)
    
    button1.when_pressed = FaixaAnterior
    button2.when_pressed = TocarEPausar
    button3.when_pressed = ProximaFaixa

    led.on()
    # loop infinito
    while True:
      metadados = player.metadata
      if metadados != None: 
        nome = player.metadata["Title"]
        lcd.clear()
        lcd.message(nome)
      sleep(0.2)