当前位置: 首页>>代码示例>>Python>>正文


Python MPDClient.fetch_idle方法代码示例

本文整理汇总了Python中mpd.MPDClient.fetch_idle方法的典型用法代码示例。如果您正苦于以下问题:Python MPDClient.fetch_idle方法的具体用法?Python MPDClient.fetch_idle怎么用?Python MPDClient.fetch_idle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mpd.MPDClient的用法示例。


在下文中一共展示了MPDClient.fetch_idle方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Radio

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]
class Radio(object):
    stations = None
    mpd = None
    position = 1
    volume = 50

    def __init__(self, stations):
        self.mpd = MPDClient()
        self.mpd.timeout = 10
        self.mpd.idletimeout = None
        self.mpd.connect("localhost", 6600)
        self.mpd.clear()
        for station in iter(stations):
            if (station != None) and (station != ""):
                self.mpd.add(station)
        self.stations = self.mpd.playlist()
        print("Successfully loaded the following playlist:")
        print(self.stations)
        print("-------")

    def increaseVolume(self):
        if self.volume < 100:
            self.volume = self.volume + 10
            self.setVolume()

    def decreaseVolume(self):
        if self.volume > 0:
            self.volume = self.volume - 10
            self.setVolume()

    def setVolume(self):
        system("amixer sset 'Master' " + str(self.volume) + "%")

    def play(self):
        system("mpc play " + str(self.position))

    def stop(self):
        system("mpc stop")

    def next(self):
        self.position = self.position + 1
        if self.position > len(self.stations):
            self.position = 1
        system("mpc play " + str(self.position))

    def prev(self):
        self.position = self.position - 1
        if self.position < 1:
            self.position = len(self.stations)
        system("mpc play " + str(self.position))

    def selectTrackUpdate(self):
        self.mpd.send_idle("currentsong")
        select([self.mpd], [], [], 10)
        self.mpd.fetch_idle()
        return self.mpd.currentsong()

    def currentStreamName(self):
        return self.streams.keys()[self.position - 1]
开发者ID:kr1schan,项目名称:tube,代码行数:61,代码来源:radio.py

示例2: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]
class MpdWatcher:
    def __init__(self, host, port):
        self.client = MPDClient()

        try:
            self.client.connect(HOST, PORT)
        except SocketError:
            print("Failed to connect to MPD, exiting")
            sys.exit(1)
        self.notify = SongNotify()

        self.song = None
        self.updateSong(self.client.currentsong())

    def watch(self):
        while True:
            self.client.send_idle()
            select([self.client], [], [])
            changed = self.client.fetch_idle()
            if "player" in changed:
                self.updateSong(self.client.currentsong())

    def updateSong(self, song):
        if not "id" in song:
            return

        if self.song and song["id"] == self.song.id:
            return

        self.song = Song(song)

        if self.client.status()["state"] == "play":
            self.notify.newSong(self.song)
        else:
            print(self.client.status()["state"])
开发者ID:vi-n,项目名称:MpdPopUp,代码行数:37,代码来源:popup.py

示例3: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]
class MpdWatcher:
    def __init__(self, host, port, verbose=False, once=False):
        self.client = MPDClient()
        self.verbose = verbose

        #try:
        #    self.client.connect(HOST, PORT)
        #except:
        #    print("Failed to connect to MPD")
        while True:
            try:
                self.client.connect(host, port)
                break
            except BaseException as e:
                print('MpdWatcher failed connecting to %s:%s: %s' % (host, port, e))
                if once:
                    sys.exit()
                time.sleep(1)
        self.notify = SongNotify(verbose=self.verbose)

        self.song = None
        self.updateSong(self.client.currentsong())

    def watch(self):
        while True:
            self.client.send_idle()
            select([self.client], [], [])
            changed = self.client.fetch_idle()
            for change in changed:
                if self.verbose == True:
                    print(["Change: ", change])
            # if set(changed).intersection(set(['player','playlist'])):
            if set(changed).intersection(set(['player'])):
                self.updateSong(self.client.currentsong())

    def once(self):
        self.updateSong(self.client.currentsong())

    def updateSong(self, song):
        self.song = Song(song)

        if self.verbose == True:
            print(["State: ", self.client.status()['state']])
        if self.client.status()['state'] == 'play':
            self.notify.newSong(self.song)
开发者ID:JustinHop,项目名称:Profile,代码行数:47,代码来源:popup.py

示例4: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]
class MPC:
  def __init__(self, host='localhost', port=6600, password=None, track=None):
    """create new MPC.
    >>> m = MPC()
    """
    if track is None:
      track = Track()
    self._client = MPDClient()

  def is_url(self, path):
    """Try to determine if the path is an URL.
    >>> m = MPC()
    >>> m.is_url(u'http://')
    True
    >>> m.is_url(u'/mymusic/artist/')
    False
    """
    # FIXME:  cover more URL types ...
    if path[:7] == "http://":
      return True
    return False

  def mpd_connect(self):
    try:
      self.client.connect(host=self.host, port=self.port)
    except SocketError as err:
      log.error(err)
      return
    if not self.password == u'':
      try:
        self.client.password(self.password)
      except CommandError as err:
        log.error(err)
        return
    log.debug(u'mpc(commands): {0}'.format(self.client.commands()))

  def mpd_disconnect(self):
    self.client.close()
    self.client.disconnect()

  def mpd_playlist(self):
    """Return the currently active playlist.
    """
    result = {}
    for entry in self._mpdfun('playlistinfo'):
      log.debug(u'mpc(playlist|entry): {0}'.format(entry))
      result[entry['id']] = entry['file']
    # log.debug(u'mpc(playlist): {0}'.format(result))
    return result

  def mpd_status(self):
    status = self._mpdfun('status')
    if status is None:
      return None
    # log.debug(u'mpc(status): {0}'.format(status))
    return status

  def _mpdfun(self, func, **kwargs):
    """Wrapper for requests to the MPD server.  Tries to re-connect if the
    connection was lost ...
    """
    for i in range(RETRIES):
      try:
        if func == 'send_idle':
          # special case, wait for an event
          self._client.send_idle()
          try:
            select([self._client], [], [])
          except error:
            # happens during shutdown and during MPDs library
            # refresh
            time.sleep(RETRY_INTERVAL)
            self.mpd_connect()
            continue
          except KeyboardInterrupt:
            self.running = False
            return None
          return self._client.fetch_idle()
        elif func == 'playlistinfo':
          return self._client.playlistinfo()
        elif func == 'status':
          return self._client.status()
      except (error, ConnectionError) as err:
        # happens during shutdown and during MPDs library refresh
        log.error(u'mpc: {0}'.format(err))
        time.sleep(RETRY_INTERVAL)
        self.mpd_disconnect()
        self.mpd_connect()
        continue
    else:
      # if we excited without breaking, we couldn't reconnect in time :(
      raise Exception(u'failed to re-connect to MPD server')
    return None

  def run(self):
    self.mpd_connect()
    self.running = True # exit condition for our main loop
    startup = True # we need to do some special stuff on startup
    now_playing = None # the currently playing song
    current_playlist = None # the currently active playlist
#.........这里部分代码省略.........
开发者ID:pscn,项目名称:yampdqmgr,代码行数:103,代码来源:mpc.py

示例5: MPDClient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]
client = MPDClient()               # create client object
# network timeout in seconds (floats allowed), default: None
client.timeout = 10
# timeout for fetching the result of the idle command is handled
# seperately, default: None
client.idletimeout = None
client.connect("localhost", 6600)  # connect to localhost:6600
print(client.mpd_version)          # print the MPD version
# print result of the command "find any house"
print(client.find("any", "house"))
# command list的机制现在还不理解,在把python-mpd2的动态方法改成静态方法的过程中,command list暂且还不能好好处理
# client.command_list_ok_begin()       # start a command list
client.update()                      # insert the update command into the list
client.status()                      # insert the status command into the list
print(client.status())
print(client.stats())
# results = client.command_list_end()  # results will be a list with the results
# print((results))
client.iterate = True
for song in client.playlistinfo():
    #print( song["file"])
    pass
client.iterate = False
client.send_idle()
events = client.fetch_idle()
print(events)
print(client.status())
client.close()                     # send the close command
client.disconnect()                # disconnect from the server
# client.delete((1,))     # delete all songs, but the first.
开发者ID:rbn42,项目名称:mpd-script,代码行数:32,代码来源:start.py

示例6: while

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]
GPIO.setup(BUTTON_VDN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(BUTTON_STOP, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.add_event_detect(BUTTON_PLAY, GPIO.FALLING, callback=play_pressed, bouncetime=bounce_time)
GPIO.add_event_detect(BUTTON_NEXT, GPIO.FALLING, callback=next_pressed, bouncetime=bounce_time)
GPIO.add_event_detect(BUTTON_PREV, GPIO.FALLING, callback=prev_pressed, bouncetime=bounce_time)
GPIO.add_event_detect(BUTTON_VUP, GPIO.FALLING, callback=vup_pressed, bouncetime=bounce_time)
GPIO.add_event_detect(BUTTON_VDN, GPIO.FALLING, callback=vdn_pressed, bouncetime=bounce_time)
GPIO.add_event_detect(BUTTON_STOP, GPIO.FALLING, callback=stop_pressed, bouncetime=bounce_time)

# Infinite Loop

try:
    while (1):
        client.send_idle()
        state = client.fetch_idle()

        if (state[0] == 'mixer'):
            data['volume'] = int(client.status()['volume'])
            data_changed_vol = True

        if (state[0] == 'player'):
            try:
                station = client.currentsong()['name']
            except KeyError:
                station = ''

            try:
                title = client.currentsong()['title']
            except KeyError:
                title = ''
开发者ID:AiGreek,项目名称:Raspberry-Scripts,代码行数:33,代码来源:MPD_LcD.py

示例7: MPDWrapper

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]
class MPDWrapper():

    def __init__(self, host, port):
        self.mpd = MPDClient(use_unicode=True)
        self.changes = Changes()
        self.host = host
        self.port = port
        self.connected = False
        self.in_idle = False

    def auth(self, password):
        if self.connected:
            try:
                self.mpd.password(password)
            except CommandError:
                return False
        return True

    def connect(self):
        try:
            self.mpd.connect(self.host, self.port)
            self.connected = True
        except SocketError:
            self.connected = False
        return self.connected

    def disconnect(self):
        if self.connected:
            self.mpd.disconnect()
            self.connected = False

    def fileno(self):
        return self.mpd.fileno()

    def get_changes(self):
        return self.changes.get() if not self.in_idle else []

    def has_changes(self):
        return len(self.changes.changes)

    def idle(self):
        if self.connected and not self.in_idle:
            self.in_idle = True
            self.mpd.send_idle()
        return self.in_idle

    def noidle(self, block=False):
        if self.connected and self.in_idle:
            self.in_idle = False
            if not block:
                self.mpd.send_noidle()
            self.changes.add(*self.mpd.fetch_idle())

    def player(self, cmd, *args):
        if self.connected:
            self.changes.add("player")
            self.noidle()
            getattr(self.mpd, cmd)(*args)

    def option(self, cmd, *args):
        if self.connected:
            self.changes.add("options")
            self.noidle()
            getattr(self.mpd, cmd)(*args)

    def status(self):
        return self.mpd.status() if self.connected else None

    def ls(self, path):
        return self.mpd.lsinfo(path) if self.connected else []

    def plchanges(self, version):
        return self.mpd.plchanges(version) if self.connected else []

    def plchangesposid(self, version):
        return self.mpd.plchangesposid(version) if self.connected else []

    def add(self, path):
        if self.connected:
            self.changes.add("playlist")
            self.noidle()
            self.mpd.add(path)

    def add_and_play(self, path):
        if self.connected:
            self.changes.add("playlist", "player")
            self.noidle()
            self.mpd.playid(self.mpd.addid(path))

    def clear(self):
        if self.connected:
            self.changes.add("playlist", "player")
            self.noidle()
            self.mpd.clear()

    def delete(self, *poslist):
        if self.connected:
            self.changes.add("playlist", "player")
            self.noidle()
            self.mpd.command_list_ok_begin()
#.........这里部分代码省略.........
开发者ID:dstenb,项目名称:tbmpcpy,代码行数:103,代码来源:wrapper.py

示例8: MPDBookmark

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]
class MPDBookmark(object):
    def __init__(self, host="localhost", port=6600, password=None,
                 motif="Podcast", field="album"):
        self.client = MPDClient()
        try:
            self.client.connect(host, port)
            if password:
               self.client.password(password) 
            
        except :
            print "merde"
            print "host = ", host
            print "port = ", port
            print "pass = ", password
            assert False
        self.motif=motif
        self.field=field
        self.boucle()

    def stats(self):
        print "==========================================="
        print "                Version :"
        print self.client.mpd_version
        print "==========================================="
        print "fin du test"
        print self.client.status()


    def wait_action(self):
        self.client.send_idle('player')
        select([self.client], [], [], 60)
        return self.client.fetch_idle()

    
    def verif_motif(self, song):
        return  self.field in song and re.match(self.motif, song[self.field])

    
    def update_song(self, song, ts):
        new_ts=time.time()
        if 'title' in song :
            print "Update song : ", song['title'],
            print "( ",int(new_ts-ts),
            print "/",song['time']," )"
        if self.verif_motif(song):
            last_up=int(new_ts-ts)
            self.client.sticker_set('song', song['file'], 
                                    'last_up', last_up)
    
    def start_song(self, new_song):
        if ('file' in new_song) and 'last_up' in self.client.sticker_list('song', new_song['file']):
            last_up=int(self.client.sticker_get('song', 
                                                new_song['file'], 
                                                'last_up'))
            if abs(int(new_song['time'])-last_up)<=4 :
                last_up=0
            self.client.seekcur(last_up)


    def boucle(self):
        

        state=self.client.status()['state']
        song=self.client.currentsong()
        print "song  :  ", song
        ts=time.time()
        if 'elapsed' in song :
            ts-=float( song['elapsed'])

        while 1 :
            ret=self.wait_action()
            new_state=self.client.status()['state']
            new_song=self.client.currentsong()

            if new_song!=song and new_song!={}:
                self.start_song(new_song)

            if song !={}:
                print "update  ",
                self.update_song(song, ts)

            state= new_state
            song= new_song
            if 'elapsed' in self.client.status():
                ts=time.time()-float( self.client.status()['elapsed'])
开发者ID:RaoulChartreuse,项目名称:mpd_bookmark,代码行数:87,代码来源:mpd_bookmark.py

示例9: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]

#.........这里部分代码省略.........
			# Check if shuffle has changed
			if (temp != self.data['shuffle']):
				changed = 0 # Shuffle has changed
				self.data['shuffle'] = temp # Update data
		except KeyError:
			pass
			
		# Get repeat all state
		try:
			temp = self.client.status()['repeat']
			if (temp == '0'):
				temp = False
			elif (temp == '1'):
				temp = True
			
			# Check if repeat all has changed
			if (temp != self.data['repeat_all']):
				changed = 1 # Repeat all has changed
				self.data['repeat_all'] = temp # Update data
		except KeyError:
			pass
			
		# Get repeat single state
		try:
			temp = self.client.status()['single']
			if (temp == '0'):
				temp = False
			elif (temp == '1'):
				temp = True
			
			# Check if repeat single has changed
			if (temp != self.data['repeat_single']):
				changed = 2 # Repeat single has changed
				self.data['repeat_single'] = temp # Update data
		except KeyError:
			pass
			
		# Return what has changed
		return changed
		
	# Function for counters (will be running in another thread)
	def timeCounter(self):
		while True:
			time.sleep(1) # Wait one second
			self.data['uptime'] += 1 # Increase uptime
			
			# If player is playing
			if (self.data['state'] == 1):
				self.data['elapsed_time'] += 1 # Increase elapsed time
				self.data['playtime'] += 1 # Increase total playtime
				
			# Time is changed, notify LCD thread
			self.LCD_client.time_change()
			
	# Function which returns data for LCD display to get it
	def getData(self):
		return self.data
			
	# Main function which is running in thread and waiting for changes
	def mpdMain(self):	
		while True:
			# Wait for any change from MPD
			self.client.send_idle()
			status = self.client.fetch_idle()
			
			# Update data
			changed = self.updateData()

			# Check if some option changed
			if (changed != -1):
				temp = False
				
				# Get changed option state
				if (changed == 0):
					# Shuffle changed
					temp = self.data['shuffle']
					
				elif (changed == 1):
					# Repeat all changed
					temp = self.data['repeat_all']
					
				elif (changed == 2):
					# Repeat single changed
					temp = self.data['repeat_single']
			
				self.LCD_client.play_mode_changed(changed, temp) # Notify LCD
			
			# Check what has changed
			try:
				type = status[0]
			except KeyError:
				continue
			
			# If volume has changed
			if (type == 'mixer'):
				self.LCD_client.volume_changed(self.data['volume'])
			
			# Else, if song or something from player changed
			elif (type == 'player'):
				self.LCD_client.data_change()
开发者ID:DustyMustard,项目名称:RuneAudioLCD,代码行数:104,代码来源:mpd_client.py

示例10: AudioManager

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import fetch_idle [as 别名]

#.........这里部分代码省略.........

	def _mpd_acquire(self):
		"""
		Allows MPD commands to be executed by the main thread.
		mpd_release() must be called afterwards to allow the idle
		thread to continue polling.
		"""
		self._locks.append(1)
		if (self._idling):
			self._mpd.noidle()
			self._idling = False

	def _mpd_release(self):
		"""Allows the idle thread to continue waiting for subsystem changes."""
		self._locks.pop()
		if (not self._locks and not self._idling):
			self._mpd.send_idle()
			self._idling = True

	def _mpd_idle(self):
		"""
		Calls `mpd idle`, which waits for a change in an MPD subsystem.
		When a change is detected, connected clients are notified and
		`mpd idle` is called again.
		"""
		self._update_current_song()
		self._mpd.send_idle()
		self._idling = True

		while True:
			can_read = select([self._mpd], [], [], 0)[0]
			if can_read and not self._locks:
				self._idling = False
				changes = self._mpd.fetch_idle()

				if 'player' in changes:
					self._update_current_song()

				self._mpd.send_idle()
				self._idling = True

			time.sleep(1)



	def seconds_to_string(self, seconds):
		"""
		Converts seconds into a time string.

		Arguments:
			seconds (int): The total number of seconds.

		Returns:
			A time string as hh:mm:ss, or mm:ss if there are no hours.
		"""
		m, s = divmod(int(float(seconds)), 60)
		h, m = divmod(m, 60)

		if h:
			return '{:d}:{:02d}:{:02d}'.format(h, m, s)
		return '{:d}:{:02d}'.format(m, s)



	def play(self):
		"""Plays the current song"""
开发者ID:nejsan,项目名称:sound_bubble,代码行数:70,代码来源:audio_manager.py


注:本文中的mpd.MPDClient.fetch_idle方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。