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


Python MPDClient.find方法代码示例

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


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

示例1: __init__

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

	def __init__( self, music_root ):
		self._music_root = music_root
		self._con = MPDClient()
		self._con.timeout = 10
		self._con.idletimeout = None
		self._con.connect( 'localhost', 6600 )

	def addToDb( self, song_obj ):
		temp = song_obj.getInfo()['file']
		while self._con.find( 'file', temp) == []:
			try:
				temp = temp.split( '/', 1 )[1]
			except IndexError:
				print( 'ERROR: Could not add.  Please put the song (if it exists) under the mpd root.' )
				break
		if self._con.find( 'file', temp) != []:
			self._con.update( temp )
		
	def listDbDir( self, dir_loc ):
		listings = []
		for listing in self._con.lsinfo( dir_loc ):
			temp = Song.Song( self._music_root + listing['file'] )
			listings.append( temp )
		return listings
	
	def __del__( self ):
		self._con.close()
开发者ID:ayypot,项目名称:ayydio,代码行数:31,代码来源:Database.py

示例2: validate_exists_and_is_not_in_playlist

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import find [as 别名]
def validate_exists_and_is_not_in_playlist(filename):
    c = MPDClient()
    c.connect("localhost", 6600)
    if len(c.playlistfind("file", filename)):
        raise forms.ValidationError("Song is already in the playlist.")
    elif not len(c.find("file", filename)):
        raise forms.ValidationError("Song not found.")
    c.disconnect()
开发者ID:allo-,项目名称:mpdsongvote,代码行数:10,代码来源:forms.py

示例3: find_track

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import find [as 别名]
def find_track(mode, key):
    client = MPDClient()
    client.connect("localhost", 6600)
    try:
        response = json.dumps(client.find(mode, key))
    except:
        response = False
    client.close()
    client.disconnect()
    return response
开发者ID:nekser,项目名称:collective_player,代码行数:12,代码来源:search.py

示例4: generate_by_artist

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import find [as 别名]
def generate_by_artist(spec):
    '''choose HOWMANY random artists, and for each one choose a random song'''
    spec.setdefault('howmany', 1)
    log.info('generating')
    conf = get_conf()
    c = MPDClient(use_unicode=True)
    c.connect(conf['MPD_HOST'], conf['MPD_PORT'])

    artists = c.list('artist')
    log.debug("got %d artists", len(artists))
    if not artists:
        raise ValueError("no artists in your mpd database")
    for _ in range(spec['howmany']):
        artist = random.choice(artists)
        yield random.choice(c.find('artist', artist))['file']
开发者ID:boyska,项目名称:larigira,代码行数:17,代码来源:audiogen_mpdrandom.py

示例5: get_track

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import find [as 别名]
def get_track(filename, in_playlist=True, client=None):
    if not client:
        c = MPDClient()
        c.connect("localhost", 6600)
    else:
        c = client

    if in_playlist:
        track = c.playlistfind('file', filename)
    else:
        track = c.find('file', filename)
    track = track[0] if track else None
    if track and 'artist' not in track:
        track['artist'] = ""
    if track and 'title' not in track:
        track['title'] = title_from_filename(track['file'])
    return track
开发者ID:allo-,项目名称:mpdsongvote,代码行数:19,代码来源:util.py

示例6: album_songs

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import find [as 别名]
def album_songs(request, album):
    c = MPDClient()
    c.connect("localhost", 6600)
    songs = filter(
        lambda x: unicode(
            x.get('title', ''),
            "utf-8",
            errors="ignore"
        ),
        c.find("album", album)
    )
    for song in songs:
        song['file'] = to_unicode(song['file'])
        song['attribution'] = get_attribution(song['file'])
    add_num_requests_to_songlist(songs)
    c.disconnect()
    return render(request, 'songs.html', {
        'page': 'album_songs',
        'album': album,
        'songs': songs
    })
开发者ID:allo-,项目名称:mpdsongvote,代码行数:23,代码来源:views.py

示例7: artist_albums

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import find [as 别名]
def artist_albums(request, artist):
    c = MPDClient()
    c.connect("localhost", 6600)
    albums = filter(
        lambda x: x,
        set(
            map(
                lambda x: unicode(
                    x.get('album', ''),
                    "utf-8",
                    errors="ignore"
                ),
                c.find("artist", artist)
            )
        )
    )
    c.disconnect()
    return render(request, 'artist.html', {
        'page': 'artist_albums',
        'artist': artist,
        'albums': albums
    })
开发者ID:allo-,项目名称:mpdsongvote,代码行数:24,代码来源:views.py

示例8: MPDClient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import find [as 别名]
from mpd import MPDClient
client = MPDClient()               # create client object
# network timeout in seconds (floats allowed), default: None
client.timeout = 10
# timeout for fetching the result of the idle command is handled
# seperately, default: None
client.idletimeout = None
client.connect("localhost", 6600)  # connect to localhost:6600
print(client.mpd_version)          # print the MPD version
# print result of the command "find any house"
print(client.find("any", "house"))
# command list的机制现在还不理解,在把python-mpd2的动态方法改成静态方法的过程中,command list暂且还不能好好处理
# client.command_list_ok_begin()       # start a command list
client.update()                      # insert the update command into the list
client.status()                      # insert the status command into the list
print(client.status())
print(client.stats())
# results = client.command_list_end()  # results will be a list with the results
# print((results))
client.iterate = True
for song in client.playlistinfo():
    #print( song["file"])
    pass
client.iterate = False
client.send_idle()
events = client.fetch_idle()
print(events)
print(client.status())
client.close()                     # send the close command
client.disconnect()                # disconnect from the server
# client.delete((1,))     # delete all songs, but the first.
开发者ID:rbn42,项目名称:mpd-script,代码行数:33,代码来源:start.py

示例9: Player

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

#.........这里部分代码省略.........
            try:
                myalbums = sorted(self.client.list('album',
                                                   'artist', myartist))
                return myalbums
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDpause(self):
        for i in xrange(5):
            try:
                self.client.pause()
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDchooseArtistsWithFirstLetter(self, chosenLetterNumber):
        """ Selects artists whose names start with
            self.artistsFirstLettersU[chosenLetterNumber] """
        if chosenLetterNumber<self.maxLetterNumber:
            chosenLetterU = self.artistsFirstLettersU[chosenLetterNumber]
        else:
            print 'Out of range'
            chosenLetterU = self.artistsFirstLettersU[0]
        msg = []
        for i, artist in enumerate(self.artists):
            if len(artist)>0:
                cU = artist.decode('utf-8')[0]
                if cU==chosenLetterU:
                    msg.append(artist)
        return msg


    def MPDwhat_song_playing(self):
        for i in xrange(5):
            try:
                return self.client.currentsong()
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')



    def MPDaddArtistAlbumToPlaylist(self, myartist, myalbum):
        for i in xrange(5):
            try:
                myplaylist = self.client.find('artist', myartist, 'album', myalbum)
                for c in myplaylist:
                    self.client.add(c['file'])
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')



    def nextLetter(self):
        if self.currentLetterNumber+1<self.maxLetterNumber:
            self.currentLetterNumber += 1
        return self.MPDchooseArtistsWithFirstLetter(
                                               self.currentLetterNumber)


    def prevLetter(self):
        if self.currentLetterNumber-1>=0:
            self.currentLetterNumber -= 1
        return self.MPDchooseArtistsWithFirstLetter(
                                               self.currentLetterNumber)


    def VolDn(self):
        vol = int(self.mixer.getvolume()[0])
        vol -= 10
        if vol < 0:
            vol = 0
        self.mixer.setvolume(vol)


    def VolUp(self):
        vol = int(self.mixer.getvolume()[0])
        vol += 10
        if vol > 100:
            vol = 100
        self.mixer.setvolume(vol)


    def currLetter(self):
        return self.MPDchooseArtistsWithFirstLetter(
                                               self.currentLetterNumber)
开发者ID:OSliusarenko,项目名称:yaih,代码行数:104,代码来源:player2.py

示例10: delete_event

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

#.........这里部分代码省略.........
                        self.tree.append([s['title']])
                    self.list[s['title']] = s['id']
                    count = count + 1
            else:
                self.current = False
                self.artist = True
                self.getMusic()
                return
        elif self.artist == True:
            artists = self.mclient.list("artist")
            artists.sort()
            self.tree.clear()
            for a in artists:
                if a != "":
                    self.tree.append([a])
                if self.hasFormer == True:
                    self.rbox.set_cursor(str(self.lartist), focus_column=None)
                    self.rbox.scroll_to_cell(str(lartist), column=None)
            self.rbox.scroll_to_cell('0', column=None)
        elif self.album == True:
            if self.nItr != None:
                #self.curartist = self.tree.get_value(self.nItr, 0)
                self.curartist = self.tree.get_value(self.tree.get_iter_from_string(str(self.rbox.get_cursor()[0][0])), 0)
            albums = self.mclient.list("album", self.curartist)
            self.tree.clear()
            for al in albums:
                if al != "":
                    self.tree.append([al])
            self.rbox.scroll_to_cell('0', column=None)
        elif self.tracks == True:
            if self.nItr != None:
                #self.curalbum = self.tree.get_value(self.nItr, 0)
                self.curalbum = self.tree.get_value(self.tree.get_iter_from_string(str(self.rbox.get_cursor()[0][0])), 0)
            tracks = self.mclient.find("album", self.curalbum)
            self.tree.clear()
            for t in tracks:
                self.tree.append([t['title']])
            self.rbox.scroll_to_cell('0', column=None)
        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()

开发者ID:vincekd,项目名称:Pilaunch,代码行数:68,代码来源:pilaunch.py

示例11: __init__

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

#.........这里部分代码省略.........
		self.update_time = 500
		
		# Read specific config file for this server
		server_config = self.config_dir+self.server
		if os.path.isfile(server_config):
			for line in open(server_config):
				if line[0]!="#":
					try:
						if "update_time" in line:
							self.update_time = int(line.split("=")[-1].strip())
						elif "folder" in line:
							self.folder = line.split("=")[-1].strip()
					except:
						print "# Error reading server config file: "+server_config
						print "# Line: "+line
		self.music_list = self.folder+".music_list"
		print "+ Using music list: "+self.music_list
		
		
	def advance(self,mode,genre):
		test_speak_mode = not mode==self.mode
		test_speak_genre = not genre==self.genre
		test_speak_track = False	
		
		if genre=="": genre=="All"

		if mode=="track":
			self.c.stop()
			self.c.clear()
			#TODO - sub
			if genre=="All":
				self.c.add("")
			else:
				self.c.findadd("genre",genre)
			self.c.random(1)
			self.c.play()
			self.genre = genre
			self.mode = mode
			
		elif mode=="album":
			if genre=="All":
				self.some_albums = list(self.albums)
				# Increment counter down through list
				if not "All" in self.i:
					self.i["All"]=len(self.some_albums)-1
				else:
					self.i["All"] = self.i["All"]-1

				if self.i["All"]<0:
					self.i["All"]=len(self.some_albums)-1
			else:
				# Build album list if genre has changed
				if not self.last_genre==genre:
					self.some_albums = []
					for a in self.albums:
						if a[0]==genre:
							self.some_albums.append(a)

				# Increment counter up through sub list
				if not genre in self.i:
					self.i[genre]=0
				else:
					self.i[genre]=self.i[genre]+1
				
				if self.i[genre]>len(self.some_albums)-1:
					self.i[genre]=0
开发者ID:Bisxuit,项目名称:dukebox,代码行数:70,代码来源:dukebox_player.py

示例12: library

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

示例13: validate_exists

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import find [as 别名]
def validate_exists(filename):
    c = MPDClient()
    c.connect("localhost", 6600)
    if not len(c.find("file", filename)):
        raise forms.ValidationError("Song not found.")
    c.disconnect()
开发者ID:allo-,项目名称:mpdsongvote,代码行数:8,代码来源:forms.py

示例14: AudioManager

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

#.........这里部分代码省略.........
		self._mpd_acquire()

		self._mpd.previous()
		self._update_current_song()

		self._mpd_release()

	def play_next_song(self):
		"""Plays the next song."""
		self._mpd_acquire()

		self._mpd.next()
		self._update_current_song()

		self._mpd_release()


	def add_new_song(self, filename):
		"""
		Updates the database and add a new file to the current playlist.

		Arguments:
			filename (str): The name of the file relative to the music directory.

		Returns:
			A dict of song data for the added song.
		"""
		self._mpd_acquire()

		self._mpd.update()
		self._mpd.idle('database') # Wait for the database to be updated
		self._mpd.add(filename)

		song = self._mpd.find('filename', filename)[0]

		self._mpd_release()

		return song

	def is_allowed_audio_file(self, filename):
		"""Returns True if the filename has an allowed audio extension."""
		return '.' in filename and filename.rsplit('.', 1)[1] in self._config['AUDIO_EXTENSIONS']

	def is_allowed_artwork_file(self, filename):
		"""Returns True if the filename has an allowed artwork extension."""
		return '.' in filename and filename.rsplit('.', 1)[1] in self._config['ARTWORK_EXTENSIONS']



	def _get_album_artwork_url(self, song_file):
		"""Returns the URL for the currently playing song's artwork.

		If the artwork does not already exist on disk, it will be
		extracted from the audio file. A resized version of the
		artwork will be created and used to reduce bandwidth.

		Arguments:
			song_file (str): The filename of the audio file.

		Returns:
			A string containing the URL for the resized artwork.
		"""
		song_file        = current.get('file', None)
		song_path        = path.join(self._config['MUSIC_DIR'], song_file)

		# The image filename is a hash of the song's filename
开发者ID:nejsan,项目名称:sound_bubble,代码行数:70,代码来源:audio_manager.py


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