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


Python MPDClient.playid方法代码示例

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


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

示例1: MyMPDClient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playid [as 别名]
class MyMPDClient():
    def __init__(self):
	## 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)

	# Auth if password is set non False
	if PASSWORD:
	    if mpdAuth(client, PASSWORD):
		print 'Pass auth!'
	    else:
		print 'Error trying to pass auth.'
		self.client.disconnect()
		sys.exit(2)
	
    def getCurrentsong(self):
	return self.client.currentsong()
	
    def pause(self):
	return self.client.pause()
    def previous(self):
	return self.client.previous()
    def _next(self):
	return self.client.next()
    def stop(self):
	return self.client.stop()

    def play(self):
	return self.client.play()

    def getStatus(self):
	return self.client.status()
    
    def add(self, item):
	self.client.add(item)
    
    def playlist(self):
	return self.client.playlist()
      
    def getPlaylistid(self):
	return self.client.playlistid()
	
    def playId(self,_id):
	self.client.playid(_id)
    
    def getItemIdInPLaylist(self, item):
      
	playlist =  self.getPlaylistid()
	for pos in playlist:
	      if pos['file'] == item:
		  return pos['id']
	return '-1'
开发者ID:9ex8,项目名称:ArduinoGround,代码行数:58,代码来源:threadedServer.py

示例2: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playid [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)
开发者ID:istehem,项目名称:RESTService,代码行数:57,代码来源:backend.py

示例3: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playid [as 别名]
class Player:
    
    def __init__(self, host="localhost", port=6600):
        self._host = host
        self._port = port
        self._client = MPDClient()
        
    def _connect(self):
        self._client.connect(self._host, self._port)
    
    def _disconnect(self):
        try:
            self._client.disconnect()           
        except:
            pass

    def _ensure__connection(self):
        try:
            self._client.ping()
        except (MPDError, ConnectionError, IOError):
            self._disconnect()
            self._connect()
        
    def play(self, stream):
        self._ensure__connection()
            
        songId = self._client.addid(stream, 0)
        self._client.playid(songId)
        
    def stop(self):
        self._ensure__connection()
        
        self._client.stop()
        
    def status(self):
        self._ensure__connection()
        
        return self._client.status()
        
    def currentsong(self):
        self._ensure__connection()
        
        return self._client.currentsong()
        
    def is_playing(self):
        status = self.status()
        
        return status['state'] == 'play'
开发者ID:n3rd,项目名称:StreamPi,代码行数:50,代码来源:Player.py

示例4: MPDWrapper

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playid [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

示例5: delete_event

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

#.........这里部分代码省略.........
        elif self.options == True:
            self.tree.clear()
            options = self.mclient.status()
            if options['consume'] == '0':
                self.tree.append(["Toggle consume [off]"])
            else:
                self.tree.append(["Toggle consume [on]"])
            if options['repeat'] == '0':
                self.tree.append(["Toggle repeat [off]"])
            else:
                self.tree.append(["Toggle repeat [on]"])
            if options['random'] == '0':
                self.tree.append(["Toggle random [off]"])
            else:
                self.tree.append(["Toggle random [on]"])
            if options['single'] == '0':
                self.tree.append(["Toggle single [off]"])
            else:
                self.tree.append(["Toggle single [on]"])
            self.rbox.scroll_to_cell('0', column=None)
        size = self.window.get_default_size()
        self.window.resize(size[0], size[1]+50)
        self.lbox.hide()
        self.scrollbox.show()
        self.window.set_focus(self.rbox)
        self.nItr = self.tree.get_iter_root()


    def mpdCmd(self):
        if self.current == True:
            songTitle = self.tree.get_value(self.tree.get_iter_from_string(str(self.rbox.get_cursor()[0][0])), 0)
            songTitle = songTitle.split("\t")[0]
            songid = self.list[songTitle]
            self.mclient.playid(songid)
            self.music = False
            #self.mclient.disconnect()
            self.destroy(self, data=None)

        elif self.artist == True:
            #artist = self.tree.get_value(self.nItr, 0)
            artist = self.tree.get_value(self.tree.get_iter_from_string(str(self.rbox.get_cursor()[0][0])), 0)
            self.mclient.add(artist)
            self.mclient.play()

        elif self.album == True:
            #album = self.tree.get_value(self.nItr, 0)
            album = self.tree.get_value(self.tree.get_iter_from_string(str(self.rbox.get_cursor()[0][0])), 0)
            self.mclient.findadd("album", album)
            self.mclient.play()

        elif self.tracks == True:
            #track = self.tree.get_value(self.nItr, 0)
            track = self.tree.get_value(self.tree.get_iter_from_string(str(self.rbox.get_cursor()[0][0])), 0)
            self.mclient.findadd("title", track)
            self.mclient.play()

        elif self.delcur == True:
            track = self.tree.get_value(self.nItr, 0)
            self.mclient.deleteid(self.list[track])
            self.current = True
            self.delcur = False
            self.getMusic()
        
        elif self.options == True:
            option = self.tree.get_value(self.nItr, 0)
            if "consume" in option and "off" in option:
开发者ID:vincekd,项目名称:Pilaunch,代码行数:70,代码来源:pilaunch.py

示例6: MPDClient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playid [as 别名]
#!/usr/bin/env python
from mpd import MPDClient
import time
maxVolume = 75
time_to_max_volume = 0.5  # TODO: Configure
mpd_host = '192.168.178.50'
mpd_port = 6600


client = MPDClient()
client.connect(mpd_host, mpd_port)
client.setvol(0)
client.playid(0)

# Push to maxVolume in time_to_max_volume
steps = 70 / (time_to_max_volume * 60)
counter = 0
while counter < maxVolume:
    client.setvol(int(counter))
    time.sleep(1)
    counter += steps

client.close()
开发者ID:flashbyte,项目名称:Minxy,代码行数:25,代码来源:alarm.py

示例7: library

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playid [as 别名]
class MPCWebSimple:
	"""Simple MPD Web Client

	GOALS
	CherryPyMPC 0.2 will be able to:
		- display playlist, file tree, and artist/album tree in different tabs
			(without reloading the whole page)
		- update the library (auto refresh when done)
		- seek in a song, graphically
		- be styled much better than 0.1 :-)

	REQS
		- python 2.x
		- python-mpd
		- cherrypy
		
	RUN
		- ./cherrypympc.py"""

# init
	def __init__(self, host, port, passw):
		self.__app__ = "CherryPyMPC 0.2 (static/iframe)"
		self.c = MPDClient()
		self.c.connect(host, port)
		if passw:
			self.c.password(passw)

# actions
	def play(self):
		self.c.play()
		raise cherrypy.HTTPRedirect("/")

	def pause(self):
		self.c.pause()
		raise cherrypy.HTTPRedirect("/")

	def stop(self):
		self.c.stop()
		raise cherrypy.HTTPRedirect("/")

	def prev(self):
		self.c.previous()
		raise cherrypy.HTTPRedirect("/")

	def next(self):
		self.c.next()
		raise cherrypy.HTTPRedirect("/")

	def playno(self, pos):
		if pos:
			self.c.playid(int(pos))
		raise cherrypy.HTTPRedirect("/")

	def addsong(self, song):
		self.c.add(song[1:-1])
		raise cherrypy.HTTPRedirect("/")

	def seek(self, pos, secs):
		self.c.seek(pos, secs)
		cherrypy.response.headers['content-type']='text/plain'
		return "OK"

	def update(self):
		self.c.update()
		cherrypy.response.headers['content-type']='text/plain'
		return "OK"

	def findadd(self, field, query, field2=None, query2=None):
		if field2 and query2:
			self.c.findadd(field, query, field2, query2)
		else:
			self.c.findadd(field, query)
		raise cherrypy.HTTPRedirect("/")

# subframe html
	def playlist(self):
		current_track = self.c.currentsong()['pos']
		plinfo = self.c.playlistinfo()
		pltable = "<table class='playlist'><tr class='header'><th>&nbsp;</th><th>Artist</th><th>Track</th><th>Lengtr</th></tr>"
		for item in plinfo:
			trclass = ""
			if item["pos"] == current_track:
				trclass = " class='currentsong'"
			pltable += "<tr{tr_class} onclick='top.location.href=\"/playno?pos={plpos}\"'><td><img src='/img/musicfile.png' /></td><td>{artist}</td><td>{title}</td><td class='tracklen'>{length}</td></tr>".format( \
					plpos=item["pos"],
					artist=item.get("artist", "&nbsp;"),
					title=item.get("title", item["file"].split("/")[-1]),
					length=SecToTimeString(item["time"]),
					tr_class=trclass)
		pltable += "</table>"
		return self.surround_head_tags_basic(pltable)

	def filetree(self):
		treelist = TreeList(self.c.list('file'))
		def make_ul(tlist, path=[], level=0):
			r = "<ul" + ("" if (level is not 0) else " class='tree'") + ">"
			if len(tlist) > 1:
				flist = sorted(tlist[1:])
				for filename in flist:
					liclass = "" if (filename is not flist[-1] or len(tlist[0].keys()) > 1) else " class='last'"
#.........这里部分代码省略.........
开发者ID:casmarrav,项目名称:cherrypympc,代码行数:103,代码来源:cherrypympc.py

示例8: MPDSwitch

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

#.........这里部分代码省略.........
    def getMPDClient(self):
        if self.client == None:
            self.client = MPDClient()
            self.client.connect("localhost", 6600)
        else:
            try:
                self.client.ping()
            except ConnectionError as e:
                self.client = None
                self.getMPDClient()

    def poll(self):
        """ This function calls itself every second to check for config changes """

        self.getMPDClient()
        state = self.getState(status=self.broadcast_status)
        if self.state != state:
            self.state = state
            state = self.getState()
            metadata = self.getMetaData()
            res = {"result":"state", "switch":self.name, "state":state, "metadata":metadata}
            self.factory.broadcast(res)
        self.factory.loop.call_later(1, self.poll)


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

    def getCurrentSong(self):
        song = self.parseSong(self.client.currentsong())
        return song

    def parseSong(self, song):
        if "artist" in song and "album" in song and "title" in song:
            song_str = "{artist} - {album}: {title}".format(**song)
        elif "title" in song:
            song_str = "{title}".format(**song)
        elif "file" in song:
            song_str = "{file}".format(**song).rpartition("/")[-1]
        else:
            song_str = "No song selected"
        return song_str

    def getState(self, song=True, playlist=True, status=True):
        self.getMPDClient()
        state = {}
        if song: state["song"] = self.getCurrentSong()
        if playlist: state["playlist"] = self.getPlaylist()
        if status: state["status"] = self.getStatus()
        return state

    def getPlaylist(self):
        self.getMPDClient()
        playlist = self.client.playlistid()
        parsed_playlist = [self.parseSong(song) for song in playlist]
        return parsed_playlist

    def getStatus(self):
        self.getMPDClient()
        status = self.client.status()
        return status

    @publicMethod
    def get_playlist(self):
        return self.getPlaylist()

    @publicMethod
    def next(self):
        self.getMPDClient()
        self.client.next()
        return True

    @publicMethod
    def stop(self):
        self.getMPDClient()
        self.client.stop()
        return True


    @publicMethod
    def previous(self):
        self.getMPDClient()
        self.client.previous()
        return True

    @publicMethod
    def pause(self):
        self.getMPDClient()
        self.client.pause()
        return True

    @publicMethod
    def play(self, data=None):
        self.getMPDClient()
        if data and "id" in data:
            self.client.playid(data["id"])
        else:
            self.client.play()
        return True
开发者ID:maschinendeck,项目名称:kommandozentrale,代码行数:104,代码来源:switch_classes.py

示例9: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playid [as 别名]
class MPDApi:
    def __init__(self, host='localhost', port='6600'):
        self.__api = MPDClient()
        self.__api.connect(host, port)

        self.__song_db = {}
        # If there are songs in the MPD queue, rebuild their info.
        for file_ in self.__api.playlist():
            file_ = file_[6:]
            song = self.playlist_find(file_)
            song_dict = self.translate_song(song)
            self.__song_db[file_] = song_dict

    @property
    def queue(self):
        queue = []
        if self.__api.currentsong():
            current_pos = int(self.__api.currentsong()['pos'])
            queue = self.__api.playlist()[current_pos:]
        return map(lambda x: x[6:], queue)

    @property
    def current_song(self):
        track = self.__api.currentsong()
        if track:
            return self.song_db.get(track['file'])
        return None

    @property
    def song_db(self):
        return self.__song_db.copy()

    def __state(self):
        return self.__api.status()['state']

    def request_song_from_api(self, search):
        search_result = self.__api.search('title', search)
        result = None
        if search_result:
            result = self.translate_song(search_result[0])
            self.__song_db[result['SongID']] = result
        return result

    def queue_song(self, file_):
        if self.__state == 'stop' and len(self.queue) == 0:
            self.__api.playid(self.playlist_find(file_)['id'])
        else:
            self.__api.add(file_)

    def auto_play(self):
        if self.__state() == 'stop' and not len(self.queue) == 0:
            while True:
                random_song = 'file: %s' % choice(self.__api.list('file'))
                if random_song not in self.__api.playlist():
                    self.queue_song(random_song)
                    break

    def remove_queue(self, file_):
        song = self.playlist_find(file_)
        if song:
            self.__api.delete(song['pos'])
            return True
        return False

    def translate_song(self, song_dict):
        result = dict(SongID=song_dict['file'])
        for key, tag in dict(SongName='title', ArtistName='artist',
                AlbumName='album').items():
            try:
                result[key] = util.asciify(song_dict[tag])
            except:
                # This song does not have that key.  Probably a .wav
                pass
        return result

    def playlist_find(self, filename):
        song = self.__api.playlistfind('file', filename)
        if song:
            return song[0]
        return None

    ###### API CALLS #######
    def api_pause(self):
        """
        Pauses the current song
        Does nothing if no song is playing
        """
        self.__api.pause()

    def api_play(self):
        """
        Plays the current song
        If the current song is paused it resumes the song
        If no songs are in the queue, it does nothing
        """
        if self.__state() == 'pause':
            self.__api.play()
        else:
            self.auto_play()

#.........这里部分代码省略.........
开发者ID:Qalthos,项目名称:groovebot,代码行数:103,代码来源:MPDApi.py

示例10: __init__

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

	def __init__(self, db = '/home/pi/radiator/radiator.sqlite3'):
		
		self.conf		= {}
		self.stations	= []
		self.homeDir	= "/home/pi/radiator"	
		
		#DB SETUP
		self.db = sqlite3.connect(db)
		self.c = self.db.cursor()
		
		#GET CONFIG
		self.c.execute('SELECT key, value FROM conf')
		for row in self.c:
			self.conf[row[0]] = row[1]

		#MPD SETUP
		self.mpd = MPDClient()
		self.mpd.connect("/var/run/mpd/socket", 6600)
		
		#SET STATIONS
		self.c.execute('SELECT id, name, url FROM stations ORDER BY stations.id DESC')
		for row in self.c: 
			self.stations.append({'id': row[0], 'name': row[1], 'url': row[2]})

		if self.conf['stationsV'] != self.conf['stationsU'] or len(self.mpd.playlistinfo()) != len(self.stations):
			self.mpd.clear()
			for st in self.stations:
				print st['url']
				st['pl_id'] = self.mpd.addid(st['url'])

			self.c.execute("UPDATE conf SET value = '%s' WHERE key = 'stationsU'" % self.conf['stationsV'])
			self.db.commit()
		else:
			for st in self.stations:
				st['pl_id'] = self.getPlStationByUrl(st['url'])['id']

		#AUTO PLAY!
		self.play()

		#SET BUTTONS AND LED
		GPIO.setwarnings(False)
		GPIO.setmode(GPIO.BCM)
		#button[0] - pin, button[1] - last state
		self.buttons = [[18, 0], [23, 0], [24, 0]]
		self.LED = 4;
		GPIO.setup(self.LED,GPIO.OUT)
		GPIO.output(self.LED, False)
		for button in self.buttons:
			GPIO.setup(button[0],GPIO.IN)
		


	def pressed(self):
		for button in self.buttons:
			input = GPIO.input(button[0])
			if ((not button[1]) and input):
				pressed = button[0]
			else:
				pressed = False;
			
			button[1] = input
			time.sleep(0.05)
			if pressed:
				return pressed
		return False

	def play(self):
		self.mpd.play();

	def next(self):
		playlist = self.mpd.playlistinfo();
		if self.mpd.currentsong()['id'] == playlist[len(playlist) - 1]['id']:
			self.mpd.playid(playlist[0]['id'])
		else:
			self.mpd.next()

	def previous(self):
		playlist = self.mpd.playlistinfo();
		if self.mpd.currentsong()['id'] == playlist[0]['id']:
			self.mpd.playid(playlist[len(playlist) - 1]['id'])
		else:
			self.mpd.previous()


	def getStByPl_id(self, id):
		for st in self.stations:
			if st['pl_id'] == id:
				return st;
		return False

	def getPlStationByUrl(self, url):
		plStations = self.mpd.playlistinfo()
		for st in plStations:
			if st['file'] == url:
				return st;
		return False

	def bookmark(self):
#.........这里部分代码省略.........
开发者ID:Grindel,项目名称:radiator,代码行数:103,代码来源:radiator.py


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