本文整理汇总了Python中mpd.MPDClient.status方法的典型用法代码示例。如果您正苦于以下问题:Python MPDClient.status方法的具体用法?Python MPDClient.status怎么用?Python MPDClient.status使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mpd.MPDClient
的用法示例。
在下文中一共展示了MPDClient.status方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [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"])
示例2: onevent
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
def onevent(msg):
# add song if needed
client = MPDClient()
client.connect("localhost", 6600)
client.use_unicode = True
if client.status()["playlistlength"] == '0' and autoaddstate == 1:
song = choose_from_list(current_list)
client.add(song)
# while client.status()['state']=='stop':
client.play()
# currentsong info
if 'player' in msg or 'playlist' in msg:
print("publish currentsong")
currentsong = client.currentsong()
print(currentsong)
# pre-treat the data if artist/title not present:
if 'title' not in currentsong.keys():
currentsong['artist'] = "?"
if 'file' in currentsong.keys():
currentsong['title'] = currentsong['file'].split('/')[-1]
yield app.session.publish('radio.updatesong', currentsong)
# player status info
if ('player' in msg or
'mixer' in msg or
'options' in msg or
'playlist' in msg):
print("publish player status")
status = client.status()
status[u'autoadd'] = autoaddstate
yield app.session.publish('radio.updatestatus', status)
# playlist info
if 'playlist' in msg:
print("publish playlist")
playlist = client.playlistinfo()
print(playlist)
playlist_trim = []
for song in playlist:
song_trim = {}
if 'http' in song['file']:
song_trim['artist'] = song['file']
song_trim['title'] = ''
song_trim['time'] = 9999
song_trim['id'] = song['id']
else:
if 'title' not in song.keys() or 'artist' not in song.keys():
song_trim['artist'] = "?"
if 'file' in song.keys():
song_trim['title'] = song['file'].split('/')[-1]
else:
song_trim['artist'] = song['artist']
song_trim['title'] = song['title']
song_trim['id'] = song['id']
song_trim['time'] = song['time']
playlist_trim.append(song_trim)
yield app.session.publish('radio.updateplaylist', playlist_trim)
client.close()
示例3: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
class Client:
client = None
def __init__(self):
self.client = MPDClient()
self.client.timeout = 10
self.client.idletimeout = None
self.client.connect("localhost", 6600)
def version(self):
return self.client.mpd_version
def getstatus(self):
return self.client.status()
def getcurrentsong(self):
return self.client.currentsong()
def getplaylist(self):
xs = []
for (id , file) in enumerate(self.client.playlistid()):
xs.append({'file' : file, 'id' : id})
return xs
def getplaylistsong(self,songid):
return self.client.playlistinfo()[songid]
def player(self,option):
if option == "pause":
self.client.pause(1)
else:
getattr(self.client, option)()
def playid(self,songid):
try:
self.client.playlistid(songid)
except:
return False
self.client.playid(songid)
return True
def getplayerstatus(self):
return self.client.status()["state"]
def previous(self):
self.client.previous()
return self.getcurrentsong()
def next(self):
self.client.next()
return self.getcurrentsong()
def random(self, active):
return self.client.random(active)
def repeat(self, active):
return self.client.repeat(active)
示例4: main
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
def main():
## MPD object instance
client = MPDClient()
mpdConnect(client, CON_ID)
status = client.status()
print status
timebuttonisstillpressed = 0
flashLED(0.1, 5)
updateLED(client)
while True:
try:
device = checkForUSBDevice("1GB") # 1GB is the name of my thumb drive
if device != "":
# USB thumb drive has been inserted, new music will be copied
flashLED(0.1, 5)
client.disconnect()
loadMusic(client, CON_ID, device)
mpdConnect(client, CON_ID)
print client.status()
flashLED(0.1, 5)
# wait until thumb drive is umplugged again
while checkForUSBDevice("1GB") == device:
sleep(1.0)
flashLED(0.1, 5)
if GPIO.input(BUTTON) == True:
if timebuttonisstillpressed == 0:
# button has been pressed, pause or unpause now
if client.status()["state"] == "stop":
client.play()
else:
client.pause()
updateLED(client)
elif timebuttonisstillpressed > 4:
# go back one track if button is pressed > 4 secs
client.previous()
flashLED(0.1, 5)
timebuttonisstillpressed = 0
timebuttonisstillpressed = timebuttonisstillpressed + 0.1
else:
timebuttonisstillpressed = 0
sleep(0.1)
log_message("foobar")
except Exception as e:
log_message(e.message)
示例5: mpd_status
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
def mpd_status():
client = MPDClient()
client.timeout = 10
client.idletimeout = None
client.connect("lounge.mpd.shack", 6600)
answer = client.currentsong()
state = client.status()
client.close()
client.disconnect()
if 'artist' in answer:
return jsonify(artist = answer['artist'],
title = answer['title'],
status = state['state'],
stream = 'false')
elif 'name' in answer:
return jsonify(name=answer['name'],
title=answer['title'],
stream='true',
status = state['state'])
elif 'file' in answer:
return jsonify(title=answer['file'],
status = state['state'],
stream='undef')
else:
return jsonify(error='unknown playback type')
return jsonify(error='unknown playback type')
示例6: connect
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
def connect(host):
'''
Connect to mpd.
'''
logger.info("Connecting to mpd on " + host)
# Parse the host address
url = urlparse('//' + host)
hostname = url.hostname
port = url.port
# Default to localhost port 6600
if hostname == None:
hostname = 'localhost'
if port == None:
port = 6600
logger.debug('Hostname: ' + hostname)
logger.debug('Port: ' + str(port))
try:
mpdc = MPDClient()
mpdc.connect(hostname, port)
logger.debug('Connection succeeded')
logger.debug('MPD status: ' + str(mpdc.status()))
except OSError as exception:
logger.info('Can not connect to mpdd on ' + host)
logger.debug('Exception: ' + str(exception.errno))
logger.debug('Message: ' + exception.strerror)
sys.exit(1)
return(mpdc)
示例7: IndiMPDClient
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
class IndiMPDClient(object):
def __init__(self):
self.config = IndiMPCConfiguration()
self.setup_dbus()
self.setup_client()
self.oldstatus = ""
self.oldsongdata = ""
pynotify.init("indimpc")
self.notification = pynotify.Notification("indiMPC started")
self.notification.set_hint("action-icons", True)
gobject.timeout_add(500, self.status_loop)
if self.config.general_grab_keys:
self.grab_mmkeys()
def setup_dbus(self):
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
self.bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
def setup_client(self):
global MPD
try:
self.mpdclient = MPDClient()
self.mpdclient.connect(self.config.mpd_host, self.config.mpd_port)
if self.config.mpd_password not in ("", None):
self.mpdclient.password(self.config.mpd_password)
self.oldstatus = self.mpdclient.status()["state"]
except socket.error, e:
sys.stderr.write("[FATAL] indimpc: can't connect to mpd. please check if it's running corectly")
sys.exit()
示例8: main
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
def main():
## MPD object instance
client = MPDClient()
if mpdConnect(client, CON_ID):
print('Got connected!')
else:
print('fail to connect MPD server.')
sys.exit(1)
# Auth if password is set non False
if PASSWORD:
if mpdAuth(client, PASSWORD):
print('Pass auth!')
else:
print('Error trying to pass auth.')
client.disconnect()
sys.exit(2)
## Fancy output
pp = pprint.PrettyPrinter(indent=4)
## Print out MPD stats & disconnect
print('\nCurrent MPD state:')
pp.pprint(client.status())
print('\nMusic Library stats:')
pp.pprint(client.stats())
client.disconnect()
sys.exit(0)
示例9: Observer
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [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
示例10: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
class MpdState:
"""
Displays MPD state, name of current song, number, etc.
:parameters:
host : str
host name of the MPD server
port : int
port number to connect to server
password : str
password
The following keys are returned:
mpdstate : MPD state, playing/stopped/paused
"""
def __init__(self, host="localhost", port=6600, password=""):
self.host = host
self.port = str(port)
self.password = password
self.client = MPDClient()
self.connected = False
def __del__(self):
try:
self.client.disconnect()
except mpd.ConnectionError:
pass
def connect(self):
try:
self.client.connect(host=self.host, port=self.port)
except SocketError:
return False
return True
def auth(self):
if self.password:
try:
client.password(self.password)
except CommandError:
return False
return True
def get(self):
d = {"mpd_state": "not connected", "mpd_title": "", "mpd_track": "", "mpd_artist": ""}
try:
mpdState = self.client.status()["state"]
songInfo = self.client.currentsong()
except:
self.connect()
self.auth()
return d
d["mpd_state"] = mpdState
if mpdState == "play":
d["mpd_track"] = safeGet(songInfo, key="track", default="00")
d["mpd_artist"] = safeGet(songInfo, key="artist", default="Unknown Artist")
d["mpd_title"] = smart_truncate(safeGet(songInfo, key="title", default="Unknown Title"), max_length=42)
return d
示例11: currentTrack
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
def currentTrack(self, i3status_output_json, i3status_config):
try:
c = MPDClient()
c.connect(host=HOST, port=PORT)
if PASSWORD:
c.password(PASSWORD)
status = c.status()
song = int(status.get("song", 0))
next_song = int(status.get("nextsong", 0))
if (status["state"] == "pause" and HIDE_WHEN_PAUSED) or (status["state"] == "stop" and HIDE_WHEN_STOPPED):
text = ""
else:
try:
song = c.playlistinfo()[song]
song["time"] = "{0:.2f}".format(int(song.get("time", 1)) / 60)
except IndexError:
song = {}
try:
next_song = c.playlistinfo()[next_song]
except IndexError:
next_song = {}
format_args = song
format_args["state"] = STATE_CHARACTERS.get(status.get("state", None))
for k, v in next_song.items():
format_args["next_{}".format(k)] = v
text = STRFORMAT
for k, v in format_args.items():
text = text.replace("{" + k + "}", v)
for sub in re.findall(r"{\S+?}", text):
text = text.replace(sub, "")
except SocketError:
text = "Failed to connect to mpd!"
except CommandError:
text = "Failed to authenticate to mpd!"
c.disconnect()
if len(text) > MAX_WIDTH:
text = text[-MAX_WIDTH-3:] + "..."
if self.text != text:
transformed = True
self.text = text
else:
transformed = False
response = {
'cached_until': time() + CACHE_TIMEOUT,
'full_text': self.text,
'name': 'scratchpad-count',
'transformed': transformed
}
return (POSITION, response)
示例12: Jukebox
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
class Jukebox():
def __init__(self):
self.dt = DisplayThread(self)
self.dt.start()
## MPD object instance
self.client = MPDClient()
if mpdConnect(self.client, CON_ID):
print 'Got connected!'
else:
print 'fail to connect MPD server.'
sys.exit(1)
try:
f = open('/media/usb/playlist.txt','r')
playlist = f.readline().rstrip()
print "Loading " + playlist
self.client.clear()
self.client.load(playlist)
except IOError:
print "Problem reading playlist"
self.client.stop()
self.client.play()
carryOn = True
while (carryOn):
if (humble.switch(0)):
time.sleep(PAUSE)
self.toggle()
if (humble.switch(1)):
time.sleep(PAUSE)
self.skip()
if (humble.switch(2)):
time.sleep(PAUSE)
self.stop()
carryOn = False
time.sleep(PAUSE)
# Stop the display thread
self.dt.done()
def skip(self):
print "Skipping"
self.client.next()
def stop(self):
print "Stopping"
self.client.stop()
humble.data.setLine(0,"")
humble.data.setLine(1,"")
humble.data.setLed('red', False)
humble.data.setLed('green', False)
time.sleep(0.5)
def toggle(self):
status = self.client.status()
if status['state'] == 'pause' or status['state'] == 'stop':
self.client.play()
else:
self.client.pause()
示例13: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
class Player:
def __init__(self):
self.client = MPDClient()
self.client.connect("localhost", 6600)
self.client.timeout = 10
self.client.idletimeout = None
def quit(self):
self.client.close()
self.client.disconnect()
def get_playlists(self):
val = self.client.listplaylists()
return val
def get_stats(self):
#{'playtime': '848', 'uptime': '2565'}
#{'songid': '33', 'playlistlength': '1', 'playlist': '86', 'repeat': '0',
#'consume': '0', 'mixrampdb': '0.000000', 'random': '0', 'state': 'play',
# 'elapsed': '7.476', 'volume': '-1', 'single': '0', 'time': '7:0', 'song': '0', 'audio': '44100:16:2', 'bitrate': '128'}
all = {}
all.update(self.client.stats())
all.update(self.client.status())
stats = {}
stats["elapsed"] = all["elapsed"] if all.has_key("elapsed") else "0"
stats["state"] = all["state"] if all.has_key("state") else "stopped"
stats["playtime"] = all["playtime"]
stats["uptime"] = all["uptime"]
stats["bitrate"] = all["bitrate"] if all.has_key('bitrate') else 0
stats["playlistlength"] = all["playlistlength"] if all.has_key("playlistlength") else 0
stats["song"] = all["song"] if all.has_key("song") else 0
# print stats
return stats
def get_playing(self):
name = "unknown"
val = self.client.currentsong()
name= val["name"] if val.has_key('name') else None
name= val["title"] if val.has_key('title') else name
# print val
return name
def load(self, list):
# print "loading list", list
self.client.clear()
self.client.load(list)
def next(self):
self.client.next()
def prev(self):
self.client.previous()
def play(self):
self.client.play()
def stop(self):
self.client.stop()
示例14: _mopidy_idle
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
def _mopidy_idle(self):
client_idle = MPDClient()
client_idle.connect(MOPIDY_HOST, MOPIDY_PORT)
while client_idle.status()['state'] != "stop":
client_idle.idle()
client_idle.close()
client_idle.disconnect()
示例15: mpd_status
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import status [as 别名]
def mpd_status(room):
if not room in mpd_room_to_port:
return jsonify({'error': 'unkown room'})
from mpd import MPDClient
client = MPDClient()
client.connect('mpd.shack', mpd_room_to_port[room])
state = client.status()['state']
return jsonify({'status': state})