本文整理汇总了Python中mpd.MPDClient.currentsong方法的典型用法代码示例。如果您正苦于以下问题:Python MPDClient.currentsong方法的具体用法?Python MPDClient.currentsong怎么用?Python MPDClient.currentsong使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mpd.MPDClient
的用法示例。
在下文中一共展示了MPDClient.currentsong方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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: MPDPoller
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [as 别名]
class MPDPoller(object):
def __init__(self, host='localhost', port='6600', password=None):
self._host = host
self._port = port
self._password = password
self._client = MPDClient()
def connect(self):
try:
self._client.connect(self._host, self._port)
except IOError as strerror:
raise PollerError("Could not connect to '%s': %s" %
(self._host, strerror))
except mpd.MPDError as e:
raise PollerError("Could not connect to '%s': %s" %
(self._host, e))
if self._password:
try:
self._client.password(self._password)
# Catch errors with the password command (e.g., wrong password)
except mpd.CommandError as e:
raise PollerError("Could not connect to '%s': "
"password commmand failed: %s" %
(self._host, e))
# Catch all other possible errors
except (mpd.MPDError, IOError) as e:
raise PollerError("Could not connect to '%s': "
"error with password command: %s" %
(self._host, e))
def disconnect(self):
try:
self._client.close()
except (mpd.MPDError, IOError):
pass
try:
self._client.disconnect()
except (mpd.MPDError, IOError):
self._client = mpd.MPDClient()
def poll(self):
try:
song = self._client.currentsong()
except (mpd.MPDError, IOError):
self.disconnect()
try:
self.connect()
except PollerError as e:
raise PollerError("Reconnecting failed: %s" % e)
try:
song = self._client.currentsong()
except (mpd.MPDError, IOError) as e:
raise PollerError("Couldn't retrieve current song: %s" % e)
print(song)
示例3: mpd
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [as 别名]
def mpd(bot, trigger):
"""Used to control the mpd music player at the space"""
rulenum = trigger.group(2)
## MPD object instance
client = MPDClient()
try:
client.connect(host=HOST, port=PORT)
except SocketError:
bot.say('socketerror')
exit(1)
# Auth if password is set non False
if PASSWORD:
try:
client.password(PASSWORD)
except CommandError:
client.disconnect()
sys.exit(2)
mpdcommand = str(rulenum)
if ((mpdcommand == 'playing') or (mpdcommand == 'state')) :
currentsong = client.currentsong()
currentstatus = client.status()
if currentstatus['state'] == 'play':
saySong(bot,currentsong)
elif currentstatus['state'] == 'pause':
bot.say('Music is currently paused (' + songNow(currentsong) + ')')
elif currentstatus['state'] == 'stop':
bot.say('No music is playing')
elif mpdcommand == 'play':
bot.say('Pressing play on mpd...')
client.play()
currentsong = client.currentsong()
saySong(bot,currentsong)
elif mpdcommand == 'pause':
bot.say('Pausing mpd...')
client.pause()
elif mpdcommand == 'stop':
bot.say('Stopping mpd...')
client.stop()
elif mpdcommand == 'next':
bot.say('Moving to next song on mpd...')
client.next()
currentsong = client.currentsong()
saySong(bot,currentsong)
else:
bot.say('invalid mpd command')
示例4: mpdInfo
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [as 别名]
def mpdInfo(host="localhost", keys=("albumartist", "album", "artist")):
result = dict()
client = MPDClient()
host = host.split(":")
try:
port = host[1]
except:
port = "6600"
host = host[0].split("@")
try:
password = host[0]
host = host[1]
except:
password = ""
host = host[0]
conId = {"host": host, "port": port}
try:
client.connect(**conId)
except SocketError:
result["error"] = "Connection to mpd failed."
return False, result
if password:
try:
client.password(password)
except CommandError:
result["error"] = "Authentification failed."
return False, result
for key in client.currentsong():
value = client.currentsong()[key]
if type(value).__name__ == "list":
value = ", ".join(value)
key = "%s" % key
if key in keys:
result[key] = value
client.disconnect()
return True, result
示例5: mpd_status
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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: onevent
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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()
示例7: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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()
示例8: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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
示例9: Play
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [as 别名]
class Play():
def __init__(self):
self.client = MPDClient() # create client object
#client.timeout = 10 # network timeout in seconds (floats allowed), default: None
#client.idletimeout = None # timeout for fetching the result of the idle command is handled seperately, default: None
def connect(self):
try:
self.client.connect(mpd_host, mpd_port)
print("MPD Version: " + self.client.mpd_version) # print the MPD version
except OSError:
print("Error connecting to MPD")
except mpd.ConnectionError:
# Already connected?
pass
def current_track_info(self):
self.connect()
try:
return self.client.currentsong()
except mpd.ConnectionError:
print("[ERROR] current_track_info(): mpd.ConnectionError")
return None
except mpd.CommandError:
print("[ERROR] play_album(): mpd.CommandError")
return None
def next_track(self):
self.connect()
try:
self.client.next()
except mpd.ConnectionError:
print("[ERROR] next_track(): mpd.ConnectionError")
except mpd.CommandError:
print("[ERROR] play_album(): mpd.CommandError")
def pause(self):
self.connect()
try:
self.client.pause()
except mpd.ConnectionError:
print("[ERROR] pause(): mpd.ConnectionError")
except mpd.CommandError:
print("[ERROR] play_album(): mpd.CommandError")
def play_album(self, album_path):
self.connect()
# mpc -h 192.168.1.80 -p 6600 listall Yeah_Yeah_Yeahs/
# Maybe you need album_path[1:]?
print("Requesting mpd play album: {}".format(album_path[1:]))
try:
self.client.clear()
self.client.add(album_path) # [1:] to strip leading /
self.client.play()
except mpd.ConnectionError:
print("[ERROR] play_album(): mpd.ConnectionError")
except mpd.CommandError:
print("[ERROR] play_album(): mpd.CommandError")
示例10: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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()
示例11: Radio
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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]
示例12: Observer
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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
示例13: get_mpd_string
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [as 别名]
def get_mpd_string():
'''
gets the current song using MPDClient library
https://github.com/Mic92/python-mpd2
$ pip install python-mpd2
'''
c = MPDClient()
c.timeout = 2
try:
c.connect('localhost', 6600)
except:
return None
status = c.status()
if status['state'] != 'play':
return None
metalist = []
song = c.currentsong()
artist = song.get('artist', None)
if isinstance(artist, list):
artist = ' / '.join(artist)
title = song.get('title', None)
if isinstance(title, list):
title = ' / '.join(title)
if artist is None and title is None:
filename = song.get('file', None)
if filename is not None:
filename = filename
filename = os.path.basename(filename).replace('_', ' ')
filename, _, ext = filename.rpartition('.')
if filename == '':
filename = ext
metalist.append(filename)
else:
if artist is not None:
metalist.append(artist)
if title is not None:
metalist.append(title)
if len(metalist) == 0:
hexchat.prnt('Metadata not found.')
return None
metastr = ' - '.join(metalist)
seconds = int(song.get('time', None))
minutes = seconds // 60
seconds = seconds % 60
d = {'meta': metastr, 'sec': seconds, 'min': minutes}
metastr = '{meta} - {min}:{sec:02d}'.format(**d)
return metastr
示例14: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [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)
示例15: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import currentsong [as 别名]
class MPD2Web:
def __init__(self):
self.client = MPDClient()
self.client.timeout = 10
self.client.idletimeout = None
self.client.connect("localhost",6600)
self.filename = 'outfile.txt'
self.server = 'localhost' # SSH host, requires password-less/key based auth
self.remotepath = '/tmp/likedsongs.md' # Change this to location on remote server.
def current_song(self):
current_song = self.client.currentsong()
self.client.close()
self.client.disconnect()
title = current_song['title']
name = current_song['name']
return "%s" % (title)
# Check to make sure we haven't accidentally liked the same song twice
# (This is only checking the last entry)
def check_last_entry(self,current):
with open(self.filename, 'r') as f:
f.seek(-2,2)
while f.read(1) != b"\n":
f.seek(-2,1)
last = f.readline()[:-1]
f.close()
if(current == last):
return False
else:
return True
def push2md(self):
now = datetime.now()
time = str(datetime.strftime(now,"%Y-%m-%d"))
currentsong = " "+time+" "+self.current_song()
if(self.check_last_entry(currentsong)):
with open(self.filename, 'a') as out:
out.write(currentsong+"\n")
out.close()
print("{} added.").format(currentsong)
else:
print("Song already added to last entry")
def push2webscp(self):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_system_host_keys()
ssh.connect(self.server, username='james')
sftp = ssh.open_sftp()
sftp.put(self.filename, self.remotepath)
sftp.close()
ssh.close()
def run(self):
self.push2md()
self.push2webscp()