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


Python MPDClient.playlist方法代码示例

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


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

示例1: Radio

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlist [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]
开发者ID:kr1schan,项目名称:tube,代码行数:61,代码来源:radio.py

示例2: MyMPDClient

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

示例3: get_paths

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlist [as 别名]
def get_paths(root):
    client = MPDClient()
    client.connect(host=HOST, port=PORT)

    if PASSWORD:
        client.password(PASSWORD)

    playlist = client.playlist()
    client.disconnect()

    return [entry.replace("file: ", root) for entry in playlist if entry.startswith("file: ")]
开发者ID:lidel,项目名称:dotfiles,代码行数:13,代码来源:mpd-playlist-export.py

示例4: MusicPlayer

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

示例5: with_mpd

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlist [as 别名]
def with_mpd(client, id, host, port):
    track = client.get('/tracks/{id}'.format(id=id))

    if track.streamable:
        stream_url = client.get(track.stream_url, allow_redirects=False)

        mpdcli = MPDClient()

        mpdcli.connect(host, port)
        ls = mpdcli.playlist()
        n = len(ls)
        id = mpdcli.addid(stream_url.location, n)
        mpdcli.addtagid(id, 'Title', track.title)
        mpdcli.addtagid(id, 'Artist', track.user['username'])

        mpdcli.close()
        mpdcli.disconnect()

        return stream_url
    else:
        return None
开发者ID:uemurax,项目名称:scc,代码行数:23,代码来源:play.py

示例6: __MPC

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

#.........这里部分代码省略.........
        self._mpdc.connect(host=self._host, port=self._port)
        pw = wc.config_get_plugin("password")
        if len(pw) > 0: self._mpdc.password(pw)

        if self.debug: wc.prnt(self.wcb or wc.current_buffer(),
                               'mpc debug: Connected')

    def currentsong(self):
        ds = self._mpdc.currentsong()
        itime = int(ds['time'])
        ipos  = int(ds['pos'])
        pct   = int(100 * (ipos / itime))

        ds.update({
            "title_or_file" : ds['title'] or splitext(basename(ds['file']))[0],
            "pos_sec"       : "%02d" % (ipos / 60),
            "pos_min"       : str(ipos / 60),
            "length_sec"    : "%02d" % (itime % 60),
            "length_min"    : str(itime / 60),
            "pct"           : "%2.0f" % pct,
            })

        return ds

    def np(self):
        """Pushes result of np template substitution to current buffer.
        """
        ds  = self.currentsong()
        if len(ds) == 0:
            wc.prnt(wc.current_buffer(), "MPC: ERROR: mpd is stopped")
            return
        wc.command(wc.current_buffer(),
                   Template(wc.config_get_plugin("format")).safe_substitute(ds))

    @_print_current
    def next(self):
        self._mpdc.next()

    @_print_current
    def pause(self):
        self._mpdc.pause()

    @_print_current
    def play(self, *args):
        self._mpdc.play()

    def playlist(self, *args):
        def ifn( b, s, d): wc.prnt(b, Template(s).safe_substitute(d))
        def cfn(): wc.prnt(None, "mpc closing playlist buffer")
        new_buf = wc.buffer_new('mpc: playlist', "ifn", "", "cfn", "")
        wc.buffer_set(new_buf, "localvar_set_no_log", "1")

        pl = self._mpdc.playlist()
        for line in pl:
            wc.prnt(new_buf, line)

        wc.buffer_set(new_buf, "display", "1")
        return pl

    def playlistinfo(self, sortkey='pos'):
        """Shows playlist information sorted by key
        """
        new_buf = wc.buffer_search("", "mpc: playlist")
        if len(new_buf) == 0:
            new_buf = wc.buffer_new('mpc: playlist', "", "", "", "")

        pl = self._mpdc.playlistinfo()
        try:
            # Numerical sort
            spl = sorted(pl,
                         cmp=lambda x,y: cmp(int(x), int(y)),
                         key=itemgetter(sortkey))
        except ValueError:
            # Alpha sort
            lcmp = lambda x,y: cmp(x.lower(), y.lower())
            spl = sorted(pl,
                         cmp=lambda x,y: cmp(x.lower(), y.lower()),
                         key=itemgetter(sortkey))

        t = Template(wc.config_get_plugin("playinfo"))
        for line in spl:
            wc.prnt(new_buf, t.safe_substitute(line))

        return pl

    @_print_current
    def previous(self):
        self._mpdc.previous()

    def random(self, *args):
        """Toggles randomness if no argument is given.
        """
        if len(args) == 0:
            args = [int(not int(self._get_status('random'))),]

        self._mpdc.random(*args)

    @_print_current
    def stop(self, *args):
        self._mpdc.stop()
开发者ID:sitaktif,项目名称:weechat-scripts,代码行数:104,代码来源:mpc.py

示例7: MusicPlayer

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

示例8: __init__

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

示例9: searchdb

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

def searchdb(query):
	print()
	for result in c.search('file',str(query)):
		print(result['file'])	
	
while True:
	x = makeChoice()
	if x == '1':
		lsdb()
	elif x == '2':
		queueUri(input('Enter uri: '))
	elif x == '3':
		c.play( 0)
	elif x == '4':
		c.next() 
	elif x == '5':
		print('Current playlist:')
		for song in c.playlist():
			print (song)
	elif x == '6':
		query = input('Search string: ')
		searchdb(query)
	elif x == 'q':
		break
c.close()
c.disconnect()

开发者ID:ayypot,项目名称:ayydio,代码行数:31,代码来源:main.py

示例10: __init__

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

示例11: player

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlist [as 别名]
def player(request):
	if request.user.is_authenticated():
		"""if "client" in session:
			client=request.session["client"]
		   else:
			client = MPDClient()
			request.session["client"] = client
		-------------------------------------------
			This does not work, as expected, pickeling such a complex object(with a connection maybe)
			raises problems, at this point it looks like we would have to create a new client object
			per page request :-(
			Unless django has a persistent object storage of some kind,
			and allows us to reference this object from the Session :-/
			When we do find a Solution for this, its simply a matter of creating the object
			if a user without one arrives or to retrieve the object if a user already has one,
			that said, we would have something like the outcommented code above, and replace
			the next 2 lines with it!



			TODO:
			+ playback
			+ search function
			+ browse inteface(?, js maybe?)
			+ maybe change to POST instead of GET?
			+ mounting your shares (should not be done on the player view!)
		"""
		## For now create a new instace everytime
		client = MPDClient()
		client.connect("localhost", 6600)
		# we should make a settings.py or some thing
		# so we can do: from settings import server, port
		list_data=[]
		index=0
		for path in client.playlist():
			list_data.append((index, basename(path)))
			index=index+1

		client = None


		perms = request.user.get_all_permissions()
		playback = False
		add = False
		rem = False
		if u'playback' in perms or request.user.is_superuser:
			playback = True
		elif u'add' in perms or request.user.is_superuser:
			add = True
		elif u'rem' in perms or request.user.is_superuser:
			rem = True
				
		
		playlist_form = forms.generate_playlist(list_data)



		return render_to_response('player.html', {'playback': playback, 'add': add, 
							 'del': rem, 'playlist': playlist_form})
	else:
		return HttpResponseRedirect('/web/')
开发者ID:kawon,项目名称:lanmpd,代码行数:63,代码来源:views.py


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