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


Python MPDClient.update方法代码示例

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


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

示例1: __init__

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

	def __init__( self, music_root ):
		self._music_root = music_root
		self._con = MPDClient()
		self._con.timeout = 10
		self._con.idletimeout = None
		self._con.connect( 'localhost', 6600 )

	def addToDb( self, song_obj ):
		temp = song_obj.getInfo()['file']
		while self._con.find( 'file', temp) == []:
			try:
				temp = temp.split( '/', 1 )[1]
			except IndexError:
				print( 'ERROR: Could not add.  Please put the song (if it exists) under the mpd root.' )
				break
		if self._con.find( 'file', temp) != []:
			self._con.update( temp )
		
	def listDbDir( self, dir_loc ):
		listings = []
		for listing in self._con.lsinfo( dir_loc ):
			temp = Song.Song( self._music_root + listing['file'] )
			listings.append( temp )
		return listings
	
	def __del__( self ):
		self._con.close()
开发者ID:ayypot,项目名称:ayydio,代码行数:31,代码来源:Database.py

示例2: Observer

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
class Observer(QThread):
    """MPD Observer thread."""
    def __init__(self):
        self._config = ServiceLocator.getGlobalServiceInstance(ServiceNames.Configuration)
        self.client = MPDClient()

        return QThread.__init__(self)

    def __del__(self):
        self.wait()

    def mpdConnect(self):
        self.client.timeout = 10
        self.client.idletimeout = None
        self.client.connect(self._config.mpdserver, self._config.mpdport)
        if len(self._config.mpdpassword) > 0:
            self.client.password(self._config.mpdpassword)
        self.client.update()

    def run(self):
        try:
            self.mpdConnect()
    
            while True:
                info = self.client.idle()
                print("info:{0}".format(info))
                if 'update' in info:
                    # Update all
                    self.updatePlaylist()
                    self.updatePlayer()
                    self.updateMixer()

                if 'playlist' in info:
                    self.updatePlaylist()
                if 'player' in info:
                    self.updatePlayer()
                    self.updateMixer()
                if 'mixer' in info:
                    self.updateMixer()
                self.sleep(2)
        except:
             self.emit(SIGNAL(ObserverSignals.ConnectionError))
            

        pass

    def updatePlaylist(self):
        playlist = self.client.playlistinfo()
        self.emit(SIGNAL(ObserverSignals.PlaylistChanged), playlist)
        pass
    def updateMixer(self):
        status = self.client.status()
        self.emit(SIGNAL(ObserverSignals.MixerChanged), status)
        pass

    def updatePlayer(self):
        currentSong = self.client.currentsong()
        self.emit(SIGNAL(ObserverSignals.PlayerChanged), currentSong)
        pass
开发者ID:huvermann,项目名称:CuteMpd,代码行数:61,代码来源:Observer.py

示例3: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
class MPDCli:
    def __init__(self, ipaddress):
        self.client = MPDClient()
        self.client.timeout = 10
        self.client.idletimeout = None
        self.client.connect(ipaddress, 6600)
        self.client.consume(0)

        self.ip = ipaddress

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

    def __tryConnect(self):
        try:
            self.client.update()
        except ConnectionError:
            self.client.connect(self.ip, 6600)
            self.client.update()

    def getNowPlaying(self):
        self.__tryConnect()
        return self.client.currentsong()

    def getCurrentStatus(self):
        self.__tryConnect()
        return self.client.status()

    def play(self):
        self.__tryConnect()

        currentState = self.client.status()['state']

        if currentState == 'stop':
            self.client.play(int(self.client.status()['song']))
        else:
            self.client.pause()

        return self.client.status()

    def stop(self):
        self.__tryConnect()
        self.client.stop()
        return self.client.status()

    def prev(self):
        self.__tryConnect()
        self.client.previous()
        return self.client.status()

    def next(self):
        self.__tryConnect()
        self.client.next()
        return self.client.status()

    def idle(self):
        self.__tryConnect()
        self.client.idle()
开发者ID:mikdsouza,项目名称:PyPiMPD,代码行数:61,代码来源:MPDC.py

示例4: connectMPD

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
def connectMPD():
    """Connect MPD service on port 6600."""
    client = MPDClient()       # create client object
    client.timeout = 10        # network timeout in seconds default: None
    client.idletimeout = None  # timeout for fetching result of idle comm.
    try:
        client.connect("localhost", 6600)  # connect to localhost:6600
        client.update()
        global MPDstatut            # get and modify MPD statut in navbar
        MPDstatut = client.status()['state']
    except Exception:
        print "Can't Connect to MPD..."
开发者ID:Badaben,项目名称:APIClock,代码行数:14,代码来源:functions.py

示例5: MusicPlayer

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
class MusicPlayer(Action):
    """MusicPlayer for Ambrosio"""
    def __init__(self, cfg):
        super(MusicPlayer, self).__init__(cfg)
        self.triggers = ["music", "audio"]
        self.mpd = MPDClient()
        self.mpd.connect("localhost", "6600")

    def _do_update(self, command):
        self.mpd.update()

    def _do_play(self, command):
        return self.mpd.play()

    def _do_add(self, command):
        canco = " ".join(command[1:])
        return self.mpd.addid(canco)

    def _do_queue(self, command):
        return "List: %s" %(self.mpd.playlist())

    def _do_songs(self, command):
        llista = self.mpd.list('file')
        print llista
        if len(llista) > 0:
            return '\n'.join(llista)
        else:
            return 'Llista buida'

    def do(self, command):
        print "Will play music ", " ".join(command)
        print command
        if command[0] == "update":
            self._do_update(command)
        elif command[0] == "songs":
            return self._do_songs(command)
        elif command[0] == "add":
            return self._do_add(command)
        elif command[0] == "play":
            return self._do_play(command)
        elif command[0] == "queue":
            return self._do_queue(command)
        else:
            return "Que?!?!?"


    def is_for_you(self, word):
        if word in self.triggers:
            return True
        return False
开发者ID:carlesm,项目名称:ambrosio,代码行数:52,代码来源:MusicPlayer.py

示例6: jouerMPD

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
def jouerMPD(path ='http://audio.scdn.arkena.com/11010/franceculture-midfi128.mp3'):
    """Play mpd with url playlist in arg."""
    client = MPDClient()    # create client object
    client.timeout = 10     # network timeout in seconds
    client.idletimeout = None
    try:
        client.connect("localhost", 6600)  # connect to localhost:6600
        client.update()
        client.clear()
        client.add(path)
        client.play()
        global MPDstatut            # get and modify MPD statut in navbar
        MPDstatut = client.status()['state']
        print MPDstatut
    except Exception:
        print "Can't Connect to MPD..."
开发者ID:Badaben,项目名称:APIClock,代码行数:18,代码来源:functions.py

示例7: main

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
def main(files, con_id=None, password=None):

    if len(files) == 0:
        return

    # First, connect to MPD. If that doesn't work, there is no use in
    # creating symlinks or doing anything else

    client = MPDClient()
    client.connect(**(con_id or CON_ID))

    if password or PASSWORD:
        mpdAuth(client, password or PASSWORD)

    # Process the command line arguments and create symlinks
    names = all_links(files)

    # if a DB update is in progress, wait for it to finish
    while still_updating(client):
        pass

    # Update the database
    client.update()

    # Wait for the database update to finish
    while still_updating(client):
        pass

    # Get the position of the first song we're going to add
    # Pos is 0-based, so no need to add 1
    pos = get_playlist_length(client);

    # Add song(s)
    for n in names:
        client.add(n)

    # Start playing if necessary
    if not is_playing(client):
        client.play(pos)

    # Clean up
    client.disconnect()

    return (pos + 1, len(names))
开发者ID:tinuzz,项目名称:traxx,代码行数:46,代码来源:mpdplay.py

示例8: AudioManager

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

#.........这里部分代码省略.........
		Arguments:
			name (str): The name of the event to fire.
		"""
		func = self._callbacks.get(name, None)
		if not func is None:
			return func(*args, **kwargs)



	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)
开发者ID:nejsan,项目名称:sound_bubble,代码行数:69,代码来源:audio_manager.py

示例9: myMPD

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
class myMPD(object):
    def __init__(self):
        self._host = mpd_config.mpd_host
        self._port = mpd_config.mpd_port
        self._password = mpd_config.mpd_pw
        self._client = MPDClient()

    def mpd_access(self, db, ac):
        """provide access-data"""
        self._host = db.ac_config_1[1]
        self._port = db.ac_config_1[2]
        self._password = db.ac_config_1[3]

    def connect(self, db, ac):
        try:
            self._client.connect(self._host, self._port)
            #self._client.connect(db.ac_config_1[1], db.ac_config_1[2])
            return True
        # Catch socket errors
        except IOError as err:
            errno, strerror = err
            db.write_log_to_db_a(ac, "MPD-IO-Error:'%s': %s" %
                    (self._host, strerror), "x", "write_also_to_console")

        except ConnectionError as e:
            db.write_log_to_db_a(ac, "MPD-Conn-Error 1: %s" % str(e), "x",
                                             "write_also_to_console")
            return None

        # Catch all other possible errors
        # ConnectionError and ProtocolError are always fatal.  Others may not
        # be, but we don't know how to handle them here, so treat them as if
        # they are instead of ignoring them.
        except MPDError as e:
            #raise RunError("Could not connect to '%s': %s" %
            #                  (self._host, e))
            db.write_log_to_db_a(ac, "MPD-Error-1: %s" % str(e), "x",
                                             "write_also_to_console")
            return None

        if self._password:
        #if db.ac_config_1[3]:
            try:
                self._client.password(self._password)
                #self._client.password(db.ac_config_1[3])
                return True
            except ConnectionError as e:
                db.write_log_to_db_a(ac, "MPD-Conn-Error 2: %s" % str(e), "x",
                                             "write_also_to_console")
                return None
            # Catch errors with the password command (e.g., wrong password)
            except CommandError as e:
                #raise RunError("Could not connect to '%s': "
                #                  "password commmand failed: %s" %
                #                  (self._host, e))
                #db.write_log_to_db_a(ac, "MPD-PW-Error: %s" % str(e), "x",
                #                             "write_also_to_console")
                return None

            # Catch all other possible errors
            except (MPDError, IOError) as e:
                #raise RunError("Could not connect to '%s': "
                #                  "error with password command: %s" %
                #                  (self._host, e))
                db.write_log_to_db_a(ac, "MPD-Error-2: %s" % str(e), "x",
                                             "write_also_to_console")
            return None

    def disconnect(self):
        # Try to tell MPD we're closing the connection first
        try:
            self._client.close()

        # If that fails, don't worry, just ignore it and disconnect
        except (MPDError, IOError):
            pass

        try:
            self._client.disconnect()

        # Disconnecting failed, so use a new client object instead
        # This should never happen.  If it does, something is seriously broken,
        # and the client object shouldn't be trusted to be re-used.
        except (MPDError, IOError):
            self._client = MPDClient()

    def exec_command(self, db, ac, command, value):
        """spread out exec commands"""
        result = None
        try:
            if command == "access":
                result = self.mpd_access(db, ac)
            if command == "play":
                result = self._client.play()
            if command == "update":
                result = self._client.update()
            if command == "song":
                result = self._client.currentsong()
            if command == "status":
                result = self._client.status()
#.........这里部分代码省略.........
开发者ID:srb-fm,项目名称:admin-srb,代码行数:103,代码来源:lib_mpd.py

示例10: MPDClient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
from mpd import MPDClient
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,代码行数:33,代码来源:start.py

示例11: get_data

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
def get_data(): 
	s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
	s.connect("mastersocket")
	s.send(json.dumps({"request": "get_data"}))
	data = s.recv(8192)
	(data, data_forecast, unread, news, cal) = json.loads(data)

	return (data, data_forecast, unread, news, cal)

(data, data_forecast, unread, news, cal) = get_data()

# Gestion Météo

id = data["weather"][0]["id"]

weather_string = get_weather_string(id);

# Synthèse vocale

tosay = "Temps prévu pour aujourd'hui : ".decode("utf-8") + weather_string.decode("utf-8") + ". Vous avez ".decode("utf-8") + str(unread[0]).decode("utf-8") + "Messages non lus : " + unread[1] + "." + str(news).decode("utf-8") + " nouvelles non lues et ".decode("utf-8") + str(cal[0]).decode("utf-8") + " évènements aujourd'hui : ".decode("utf-8") + cal[1]

client = MPDClient()
client.connect("localhost", 6600)

subprocess.call(["pico2wave", "-l", "fr-FR", "-w" "/var/lib/mpd/music/temp.wav", tosay.encode("utf-8")])
client.clear()
client.update()
client.add("temp.wav")
client.play()
client.disconnect()
开发者ID:konfiot,项目名称:PRoq,代码行数:32,代码来源:tts.py

示例12: MusicPlayer

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
class MusicPlayer(Action):
    """MusicPlayer for Alfred"""
    def __init__(self, cfg):
        super(MusicPlayer, self).__init__(cfg)
        self.triggers = ["music","audio"]
        self.mpd = MPDClient()
        self.mpd.connect("localhost", "6600")
        self.mpd.consume(0)

    def _do_update(self, command):
        self.mpd.update()

    def _do_list(self, command):
        llista = self.mpd.list('file')
        print llista
        if len(llista) > 0:
            return "\n".join(llista)
        else:
            return "Empty List SIR"

    def _do_add(self, command):
        song = " ".join(command[1:])
        self.mpd.add(song)
        return "Song %s Added SIR" % (song)

    def _do_queue(self,command):
        return "list: %s" % (self.mpd.playlist())

    def _do_clear(self, command):
        self.mpd.clear()
        return "Clear Done SIR"

    def _do_next(self, command):
        self.mpd.next()
        return "Next Song Done SIR"

    def _do_previous(self, command):
        self.mpd.previous()
        return "Previous Song Done SIR"

    def _do_pause(self, command):
        self.mpd.pause()
        return "Music Paused SIR"

    def _do_shuffle(self, command):
        self.mpd.shuffle()
        return "Music shuffled SIR"

    def _do_repeat(self, command):
        try:
            if command[1] == "on":
                self.mpd.repeat(1)
                return "Repeat Set On SIR"
            elif command[1] == "off":
                self.mpd.repeat(0)
                return "Repeat Set Off SIR"
            else:
                return "Error SIR"
        except:
            return "Error SIR"

    def _do_play(self, command):
        try:
            songpos = command[1]
            self.mpd.play(int(songpos))
            return "Playing %s Song Done SIR" % (songpos)
        except:
            self.mpd.play()
            return "Music Playing SIR"

    def _do_stop(self, command):
        self.mpd.stop()
        return "Music Stoped SIR"

    def do(self, command):
        print "Will", " ".join(command), "music"
        print command
        if command[0] == "update":
            self._do_update(command)
        elif command[0] == "list":
            return self._do_list(command)
        elif command[0] == "add":
            return self._do_add(command)
        elif command[0] == "queue":
            return self._do_queue(command)
        elif command[0] == "play":
            return self._do_play(command)
        elif command[0] == "stop":
            return self._do_stop(command)
        elif command[0] == "clear":
            return self._do_clear(command)
        elif command[0] == "next":
            return self._do_next(command)
        elif command[0] == "previous":
            return self._do_previous(command)
        elif command[0] == "pause":
            return self._do_pause(command)
        elif command[0] == "repeat":
            return self._do_repeat(command)
        elif command[0] == "shuffle":
#.........这里部分代码省略.........
开发者ID:Costar93,项目名称:Alfred,代码行数:103,代码来源:MusicPlayer.py

示例13: MPDWrapper

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

#.........这里部分代码省略.........
    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()
            for p in poslist:
                self.mpd.delete(p)
            self.mpd.command_list_end()

    def update(self, path=""):
        if self.connected:
            self.noidle()
            self.mpd.update(path)

    def playlist_song(self, songid):
        return Song(self.mpd.playlistid(songid)[0])

    # Fallback if seekcur command isn't available
    def _seekcur_fallback(self, posstr):
        status = self.status()
        time = posstr
        if any(posstr.startswith(c) for c in "+-"):
            time = str(elapsed_sec(status) + int(posstr))
        getattr(self.mpd, "seek")(status.get("song", "-1"), time)

    def seekcur(self, posstr):
        if self.connected:
            self.changes.add("player")
            self.noidle()
            try:
                getattr(self.mpd, "seekcur")(posstr)
            except CommandError as e:
                if not unknown_command_error(e, "seekcur"):
                    raise
                self._seekcur_fallback(posstr)

    def current_song(self):
        d = self.mpd.currentsong()
        return Song(d) if d else None
开发者ID:dstenb,项目名称:tbmpcpy,代码行数:104,代码来源:wrapper.py

示例14: Player

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import update [as 别名]
class Player():
    """ Main class. Supports communicating with MPD """

    connected_to_mpd = False
    currentLetterNumber = 0
    maxLetterNumber = 0

    def __init__(self):
        """ Coonects to MPD, prints version """
        self.client = MPDClient()               # create client object
#        self.client.timeout = 10                # network timeout in seconds (floats allowed), default: None
#        self.client.idletimeout = None          # timeout for fetching the result of the idle command is handled seperately, default: None

        self.MPDserverconnect()
        self.mixer = alsaaudio.Mixer(control='PCM', id=0, cardindex=1)

    def MPDnext(self):
        for i in xrange(5):
            try:
                self.client.next()
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDprev(self):
        for i in xrange(5):
            try:
                self.client.previous()
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDserverconnect(self):
        try:
            self.client.connect("localhost", 6600)  # connect to piplay:6600
            print 'MPD version',
            print(self.client.mpd_version)          # print the MPD version
            self.connected_to_mpd = True
        except:
            self.connected_to_mpd = False


    def MPDserverDisconnect(self):
        for i in xrange(5):
            try:
                self.client.close()                     # send the close command
                self.client.disconnect()                # disconnect from the server
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDstatus(self):
        for i in xrange(5):
            try:
                return self.client.status()
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDupdateDatabase(self):
        """ Updates MPD's music database """
        for i in xrange(5):
            try:
                self.client.update()
                print('Updating music database...')
                while 'updating_db' in self.client.status():
                    sleep(1)
                print('Done!')
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDclearPlayList(self):
        for i in xrange(5):
            try:
                self.client.clear()
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
#.........这里部分代码省略.........
开发者ID:OSliusarenko,项目名称:yaih,代码行数:103,代码来源:player2.py

示例15: __init__

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

    def __init__(self, channelList):
        print ("Taste drücken, um Song abzuspielen, CTRL+C beendet das Programm.")
        self.client = MPDClient()
        # Configure MPD connection settings
        self.host = 'localhost'
        self.port = '6600'
        self.initGPIO(channelList)
        self.updateAndLoadLatestsPlaylist()
        self.stopPlaybackAfterCurrentSong()
        self.andNowWaitForButtonClicksAndHandleThem()

    def initGPIO(channelList):
        print("Initializing GPIO pins ...")
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(channelList, GPIO.IN)

    @contextmanager
    def connectionToMpdServer(self):
        try:
            self.client.connect(self.host, self.port)
            yield
        finally:
            self.client.close()
            self.client.disconnect()

    def updateAndLoadLatestsPlaylist(self):
        with self.connectionToMpdServer():
            print('Loading playlist ...')
            self.client.update()
            self.client.clear()
            os.system("mpc ls | mpc add")
            print self.client.playlist()
            print('--------------------')

    def stopPlaybackAfterCurrentSong(self):
        with self.connectionToMpdServer():
            self.client.single(1)

    def andNowWaitForButtonClicksAndHandleThem(self):
        while True:
            if GPIO.input(PLAY01) == True:
                self.handleButtonClick(self.client, '0')
            if GPIO.input(PLAY02) == True:
                self.handleButtonClick(self.client, '1')
            if GPIO.input(PLAY03) == True:
                self.handleButtonClick(self.client, '2')

            sleep(0.1);

    def handleButtonClick(self, client, song):
        with self.connectionToMpdServer():
            status = self.client.status()["state"]

            if (status == "play" or status == "pause"):
                if self.client.currentsong()["pos"] == song:
                    self.client.pause()
                elif self.client.currentsong()["pos"] != song:
                    self.client.stop()
                    self.client.play(song)
            elif status == "stop":
                self.client.play(song)
            else:
                print("Error")
开发者ID:Bussmeyer,项目名称:miek,代码行数:67,代码来源:player.py


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