本文整理汇总了Python中mpd.MPDClient类的典型用法代码示例。如果您正苦于以下问题:Python MPDClient类的具体用法?Python MPDClient怎么用?Python MPDClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MPDClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run():
if not request.form['url']:
flash('Please provide an URL')
return redirect(url_for('welcome'))
# do stuff
try:
p = subprocess.check_output(['/usr/bin/python', 'youtube-dl', '-t', '--no-progress', '--extract-audio', '--max-quality=18', '--audio-format=mp3', '--', request.form['url']])
except:
flash("Nice try.")
return redirect(url_for('welcome'))
m = re.search("\[ffmpeg\] Destination: (.+?)\s", p)
myfile = m.group(1)
shutil.move(myfile, "static/%s" % myfile)
try:
mpd = MPDClient()
try:
mpd.connect(host="trillian", port="6600")
mpd.add("http://toolbox.labor.koeln.ccc.de/static/%s" % myfile)
except:
raise
except:
flash('mpd failure')
return redirect(url_for('welcome'))
flash('your song has been added to the playlist')
return redirect(url_for('welcome'))
示例2: fav_song
def fav_song(request):
c = MPDClient()
c.connect("localhost", 6600)
form = FavSongForm(request.POST or None)
if not form.is_valid():
for error in form.errors:
messages.add_message(
request,
messages.ERROR,
"Error: {0}".format(form.errors[error][0])
)
else:
filename = form.cleaned_data['filename']
track = get_track(filename, in_playlist=False)
if not track:
messages.add_message(
request,
messages.ERROR,
"Error: Cannot find song."
)
else:
messages.add_message(
request,
messages.INFO,
"Faved: {artist} - {title}".format(
artist=track['artist'], title=track['title'])
)
song_obj = get_song(filename, track['artist'], track['title'])
SongFav(song=song_obj).save()
return redirect(request.GET.get("from", "/"))
示例3: play_id
def play_id(play_id):
client = MPDClient()
client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
client.timeout = None
client.idletimeout = None
client.playid(play_id)
return redirect(url_for('player'))
示例4: __enter__
def __enter__(self):
client = MPDClient(use_unicode=True)
self.client = client
client.timeout = 1
client.idletimeout = None
client.connect("131.urlab.be", 6600)
return client
示例5: request_song
def request_song(request):
c = MPDClient()
c.connect("localhost", 6600)
form = RequestSongForm(request.POST or None)
if not form.is_valid():
for error in form.errors:
messages.add_message(
request,
messages.ERROR,
"Error: {0}".format(form.errors[error][0])
)
else:
filename = form.cleaned_data['filename']
track = get_track(filename, in_playlist=False)
if not track:
messages.add_message(
request,
messages.ERROR,
"Error: Cannot find song."
)
else:
messages.add_message(
request,
messages.INFO,
"Requested: {artist} - {title}".format(
artist=track['artist'], title=track['title'])
)
song_obj = get_song(filename, track['artist'], track['title'])
sr, created = SongRequest.objects.get_or_create(
song=song_obj,
)
sr.save() # safe SongRequest anyway to update timestamp
SongRequestVote(songrequest=sr, value=+1).save()
return redirect(request.GET.get("from", "/"))
示例6: yoinkMPD
def yoinkMPD(cod):
mpd = MPDClient(use_unicode=True)
mpd.timeout = None
mpd.idletimeout = None
mpd.connect(cod.config["mpd"]["host"], cod.config["mpd"]["port"])
return mpd
示例7: delegateInput
def delegateInput(self, text):
"""A wrapper for querying brain."""
got_hit = False
# check if input is meant to start the music module
if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
# check if mpd client is running
try:
client = MPDClient()
client.timeout = None
client.idletimeout = None
client.connect("localhost", 6600)
except:
self.logger.warning("Failed to init MPDClient")
self.mic.say("Wybacz, ale najwyraźniej usługa Spotify nie działa")
return
self.logger.info("waiting for Spotify playlist")
self.mic.say("Poczekaj chwilę, wczytuję listę utworów Spotify")
music_mode = MusicMode(self.persona, self.mic, self.logger)
music_mode.handleForever()
return
else:
if " następnie " in lowerUTF8(text):
l_text = text.split(" następnie ")
for text in l_text:
new_got_hit = self.brain.query(text)
got_hit = got_hit or new_got_hit
else:
got_hit = self.brain.query(text)
return got_hit
示例8: IndiMPDClient
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()
示例9: connect
def connect(self,port):
global client
connection = False
retry = 2
while retry > 0:
client = MPDClient() # Create the MPD client
try:
client.timeout = 10
client.idletimeout = None
client.connect("localhost", port)
log.message("Connected to MPD port " + str(port), log.INFO)
connection = True
retry = 0
except:
log.message("Failed to connect to MPD on port " + str(port), log.ERROR)
time.sleep(0.5) # Wait for interrupt in the case of a shutdown
log.message("Restarting MPD",log.DEBUG)
if retry < 2:
self.execCommand("service mpd restart")
else:
self.execCommand("service mpd start")
time.sleep(2) # Give MPD time to restart
retry -= 1
return connection
示例10: delegateInput
def delegateInput(self, texts):
"""A wrapper for querying brain."""
# check if input is meant to start the music module
for text in texts:
if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
self._logger.debug("Preparing to start music module")
# check if mpd client is running
try:
client = MPDClient()
client.timeout = None
client.idletimeout = None
client.connect("localhost", 6600)
except:
self._logger.critical("Can't connect to mpd client, cannot start music mode.", exc_info=True)
self.mic.say(
"I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify.")
return
self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
self._logger.debug("Starting music mode")
music_mode = MusicMode(self.persona, self.mic)
music_mode.handleForever()
self._logger.debug("Exiting music mode")
return
self.brain.query(texts)
示例11: connect_to_mpd
def connect_to_mpd(self):
client=MPDClient()
try:
client.connect(MPDHost, MPDPort)
return client
except SocketError:
print "Unable to connect to MPD on %s on port %s" % (MPDHost, MPDPort)
示例12: connect
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)
示例13: MPDPoller
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)
示例14: currentTrack
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)
示例15: Observer
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