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


Python MPDClient.playlistid方法代码示例

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


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

示例1: __init__

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

示例2: MyMPDClient

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

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlistid [as 别名]
def playlist(request):
    c = MPDClient()
    c.connect("localhost", 6600)
    update_playlist(client=c)
    playlist = c.playlistid()
    status = c.status()

    # add position in current song
    if len(playlist):
        playlist[0]['cur_time'] = status['time'].split(":")[0]

    votes = get_votes()
    favs = dict([
        (x['filename'], x['favs']) for x in Song.objects.all().annotate(
            favs=models.Count("songfav")
        ).values("filename", "favs")])
    for song in playlist:
        song['file'] = to_unicode(song['file'])
        if song['file'] in favs:
            song['favs'] = favs[song['file']]
        else:
            song['favs'] = 0

        if song['file'] in votes:
            song['votes'] = votes[song['file']]
        else:
            song['votes'] = 0

        song['attribution'] = get_attribution(song['file'])

    current_songid = c.status()['songid']
    c.disconnect()
    return render(request, 'playlist.html', {
        'page': 'playlist',
        'current_songid': current_songid,
        'playlist': playlist,
        'status': status
    })
开发者ID:allo-,项目名称:mpdsongvote,代码行数:40,代码来源:views.py

示例4: getData_Mpd

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlistid [as 别名]
def getData_Mpd(target):
    if target in clients or isAvailable(*target):
        if target in clients:
            client = clients[target]
        else:
            from mpd import MPDClient
            client = MPDClient()
            client.timeout = 0.5
            client.idletimeout = None
            client.connect(*target)
            clients[target] = client
        status = client.status()
        if status['state'] not in ["play", "pause"]:
            return None
        result = {}
        def secondsToDuration(secs):
            minutes = secs // 60
            secs = secs % 60
            return "%02i:%02i" % (minutes, secs)
        time = int(status["time"].split(":")[0])
        duration = int(status["time"].split(":")[1])
        if status["state"] == "play":
            result["PlayStatus"] = "Playing"
        else:
            result["PlayStatus"] = "Paused"
        result["Time"] = secondsToDuration(time)
        result["Duration"] = secondsToDuration(duration)

        if float(duration > 0):
            result["Percentage"] = "%i" % ((time / float(duration)) * 100)
        playlist = client.playlistid(status["songid"])
        for i in ["album", "artist", "title"]:
            if i in playlist[0]:
                result[i.title()] = playlist[0][i]
        result["Type"] = "Audio"
        return result
开发者ID:404d,项目名称:.dot,代码行数:38,代码来源:nowplaying.py

示例5: main

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlistid [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 song:'
    pp.pprint(client.currentsong())
    pp.pprint(client.currentsong()['file'])
    pos = client.currentsong()['pos'];
    song_in_playlist = client.playlistid(pos)
    pp.pprint(song_in_playlist)
    print '\nCurrent MPD state:'
    ##pp.pprint(client.status())

    print '\nMusic Library stats:'
    ##pp.pprint(client.stats())

    client.disconnect()
    sys.exit(0)
开发者ID:abednarski79,项目名称:mpd-lirc,代码行数:38,代码来源:TestConnection.py

示例6: MPDWrapper

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

#.........这里部分代码省略.........
    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()
            for p in poslist:
                self.mpd.delete(p)
            self.mpd.command_list_end()

    def update(self, path=""):
        if self.connected:
            self.noidle()
            self.mpd.update(path)

    def playlist_song(self, songid):
        return Song(self.mpd.playlistid(songid)[0])

    # Fallback if seekcur command isn't available
    def _seekcur_fallback(self, posstr):
        status = self.status()
        time = posstr
        if any(posstr.startswith(c) for c in "+-"):
            time = str(elapsed_sec(status) + int(posstr))
        getattr(self.mpd, "seek")(status.get("song", "-1"), time)

    def seekcur(self, posstr):
        if self.connected:
            self.changes.add("player")
            self.noidle()
            try:
                getattr(self.mpd, "seekcur")(posstr)
            except CommandError as e:
                if not unknown_command_error(e, "seekcur"):
                    raise
                self._seekcur_fallback(posstr)

    def current_song(self):
        d = self.mpd.currentsong()
        return Song(d) if d else None
开发者ID:dstenb,项目名称:tbmpcpy,代码行数:104,代码来源:wrapper.py

示例7: __init__

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

#.........这里部分代码省略.........
	def undo(self):
		# Reverse the last action (i.e. back to the last time save_state() was called)
		self.c.stop()
		self.c.clear()
		this_song = self.last_song
		this_time = self.last_time

		if self.last_mode=="track":
			if self.genre=="" or self.genre=="All":
				self.c.add("/")			
			else:
				self.c.findadd("genre",self.genre)
			self.c.random(1)
			self.c.play()
		elif self.last_mode=="album":
			self.mode = "album"
			self.c.random(0)
			self.play_album(self.last_album,self.last_artist)
		
		# Attempt to seek to the previous track and album
		try:
			if this_song and this_time:
				self.c.seek(this_song,int(round(float(this_time))))
			elif this_song:
				self.c.play(this_song)
		except:
			print "# Could not seek to song and track"
		
		
	def generate_track_lengths(self):
		# Build list of track lengths (used for display)
		self.track_lengths = []
		self.track_names = []
		for track in self.c.playlistid():
			if track.get("time","")<>"":
				self.track_lengths.append(float(track.get("time","")))
				self.track_names.append(track.get("title",""))


	def generate_album_list(self):
		print "+ Updating MPD database"
		self.c.update() #need to wait for this somehow

		# TODO - check for file
		fid = open(self.music_list,'wt')
		all_genres = list(self.c.list('genre'))
		self.albums=[]
		print "+ Generating database..."
		t_songs = 0
		t_albums = 0		
		
		for g in all_genres:
			if not (g=="" or g=="Video"):
				songs = self.c.find('genre',g)
				self.n[g] = len(songs)
				t_songs+=len(songs)
				print "  - "+g+": "+str(len(songs))
				for s in songs:
					# Get the artist and album for this song, with defaults if blank or absent
					temp = [g,s.get('artist','Various'),s.get('album','Other')]
					if not temp in self.albums:
						fid.write(temp[0]+'/'+temp[1]+'/'+temp[2]+'\n')
						t_albums+=1
						self.albums.append(temp)
			elif g=="":
				blank_albums = []
开发者ID:Bisxuit,项目名称:dukebox,代码行数:70,代码来源:dukebox_player.py

示例8: player

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlistid [as 别名]
class player():

    """Play arg "radio" in local HTML player."""

    def __init__(self):
        """Connection init."""
        self.client = MPDClient()
        self.client.timeout = 10
        self.client.idletimeout = None
        self.client.connect("localhost", 6600)

    def clear(self):
        """Clear player playlist."""
        self.client.clear()

    def play(self, media):
        """Start player with media(url) arg."""
        self.client.clear()
        if media:
            self.client.add(media)
            self.client.setvol(60)
            self.client.play()

    def podlist(self, media):
        """Get podcast infos(parsed)."""
        parsed = podcastparser.parse(media, urllib.urlopen(media))
        return parsed

    def stop(self):
        """Stop player."""
        self.client.stop()

    def volup(self, n=10):
        """Set player volume up."""
        status = self.client.status()
        nvol = int(status['volume']) + n
        if nvol > 100:
            nvol = 100
        self.client.setvol(nvol)

    def voldown(self, n=10):
        """Set player volume down."""
        status = self.client.status()
        volume = status['volume']
        nvol = int(volume) - n
        if nvol < 0:
            nvol = 0
        self.client.setvol(nvol)
        print "Volume : %d" % nvol

    def status(self):
        """Get player status."""
        status = self.client.status()

        monstatus = {}

        for key, value in status.items():
            monstatus[key] = value.encode('utf-8')

        time.sleep(2)
        maplaylist = self.client.playlistid()
        try:
            for key, value in maplaylist[0].items():
                monstatus[key] = value.decode('utf-8')
        except:
            pass
        return monstatus, maplaylist

    def is_playing(self):
        """Verify player playing."""
        status = self.status()
        if status['state'] == 'stop':
            return False
        else:
            return True
开发者ID:jeromefiot,项目名称:web_apiclock,代码行数:77,代码来源:mympd.py

示例9: player

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlistid [as 别名]
class player():

    """Play arg "radio" in local HTML player."""

    def __init__(self):
        """Connection init."""
        self.client = MPDClient()
        self.client.timeout = 10
        self.client.idletimeout = None
        try:
            self.client.connect("localhost", 6600)
            self.client.update()
        except Exception:
            print "Can't Connect to MPD..."

    def clear(self):
        """Clear player playlist."""
        self.client.clear()

    def play(self,
        media="http://audio.scdn.arkena.com/11010/franceculture-midfi128.mp3"):
        """Start player with media(url) arg."""
        self.client.clear()
        self.client.add(media)
        self.client.setvol(60)
        self.client.play()

    def podlist(self, media):
        """Get podcast infos(parsed)."""
        parsed = podcastparser.parse(media, urllib.urlopen(media))
        return parsed

    def stop(self):
        """Stop player."""
        self.client.stop()

    def volup(self, n=10):
        """Set player volume up."""
        status = self.client.status()
        nvol = int(status['volume']) + n
        if nvol > 100:
            nvol = 100
        self.client.setvol(nvol)

    def voldown(self, n=10):
        """Set player volume down."""
        status = self.client.status()
        volume = status['volume']
        nvol = int(volume) - n
        if nvol < 0:
            nvol = 0
        self.client.setvol(nvol)
        print "Volume : %d" % nvol

    def status(self):
        """Get player status."""
        status = self.client.status()

        monstatus = {}

        for key, value in status.items():
            monstatus[key] = value.encode('utf-8')

        time.sleep(2)
        maplaylist = self.client.playlistid()
        try:
            for key, value in maplaylist[0].items():
                monstatus[key] = value.decode('utf-8')
        except:
            pass
        return monstatus

    def is_playing(self):
        """Verify player playing and update globale MPDstatut."""
        stat = self.status()
        if stat['state'] != None:
            MPDstatut = stat['state']
        else:
            MPDstatut = None
        return MPDstatut
开发者ID:Badaben,项目名称:APIClock,代码行数:82,代码来源:mympd.py

示例10: MPDSwitch

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlistid [as 别名]
class MPDSwitch(SwitchClass):
    class_metadata = {"type":"music"}
    metadata = {}
    client = None
    state = {}
    broadcast_status = False
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.getMPDClient()
        self.poll()

    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()
#.........这里部分代码省略.........
开发者ID:maschinendeck,项目名称:kommandozentrale,代码行数:103,代码来源:switch_classes.py

示例11: playlist_vote

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import playlistid [as 别名]
def playlist_vote(request, up):
    c = MPDClient()
    c.connect("localhost", 6600)
    update_playlist(client=c)

    form = PlaylistVoteForm(request.POST or None)
    if not form.is_valid():
        for error in form.errors:
            messages.add_message(
                request, messages.ERROR,
                "{0}".format(form.errors[error][0])
            )
        return redirect(reverse(playlist))
    filename = form.cleaned_data['filename']

    pl = c.playlistid()
    track = get_track(filename, in_playlist=True, client=c)

    # track not in playlist
    if not track:
        return redirect(reverse(playlist))

    song_obj = get_song(filename, track['artist'], track['title'])
    pv = PlaylistVote(song=song_obj, value=+1 if up else -1)
    pv.save()

    if up:
        voted_text = "Voted up: {artist} - {title}"
    else:
        voted_text = "Voted down: {artist} - {title}"

    messages.add_message(
        request, messages.INFO, voted_text.format(
            artist=track.get("artist", "unknown artist"),
            title=track.get("title", "unknown title")
        )
    )

    votes = get_votes()
    song_votes = votes.get(filename, 0)
    songid = int(track['id'])
    pos = int(track['pos'])
    movepos = None

    # remove, if there are enough negative votes
    if song_votes <= REMOVE_FROM_PLAYLIST_VOTES:
        c.delete(pos)
        update_playlist(client=c)
        remove_text = "removed: {artist} - {title}"
        messages.add_message(
            request, messages.INFO, remove_text.format(
                artist=track.get("artist", "unknown artist"),
                title=track.get("title", "unknown title")
            )
        )
    elif up:
        # pos -1 .. 1 (never move before the first (playing) song)
        for plpos in xrange(pos-1, 0, -1):
            pl[plpos]['file'] = to_unicode(pl[plpos]['file'])
            if song_votes - MIN_MOVE_DIFFERENCE \
               >= votes.get(pl[plpos]['file'], 0):
                    movepos = plpos
    else:
        # pos+1 .. end
        for plpos in xrange(pos+1, len(pl)):
            pl[plpos]['file'] = to_unicode(pl[plpos]['file'])
            if song_votes + MIN_MOVE_DIFFERENCE \
               <= votes.get(pl[plpos]['file'], 0):
                    movepos = plpos
            else:
                break

    if movepos is not None:
        c.moveid(songid, movepos)
        if up:
            voted_text = "Moved up: {artist} - {title}"
        else:
            voted_text = "Moved down: {artist} - {title}"
        messages.add_message(
            request, messages.INFO, voted_text.format(
                artist=track.get("artist", "unknown artist"),
                title=track.get("title", "unknown title")
            )
        )

    c.disconnect()
    return redirect(reverse(playlist))
开发者ID:allo-,项目名称:mpdsongvote,代码行数:89,代码来源:views.py


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