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


Python MPDClient.random方法代码示例

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


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

示例1: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
class mpd_client:
    def __init__(self):
        self.client = MPDClient()
        self.connect()

    def connect(self):
        self.client.timeout = None
        self.client.idletimeout = None
        self.client.connect("192.168.1.153", 6600)

    def playing(self):
        if self.client.status()["state"] == "play":
            return True
        else:
            return False

    def stop(self):
        self.client.stop()
        self.client.clear()
        self.client.random(0)

    def instant(self):
        self.client.clear()
        self.client.load("AlarmPlaylist")
        self.client.random(1)
        self.client.play()

    def mpd_command(self, command):
        client = self.client
        dict = {
            "play": client.play,
            "pause": client.pause,
            "stop": self.stop,
            "next": client.next,
            "previous": client.previous,
            "instant": self.instant,
        }
        try:
            if command not in ["vol up", "vol down"]:
                dict[command]()
            elif command == "vol up":
                vol = int(client.status()["volume"])
                if vol != -1 and vol < 99:
                    client.setvol(vol + 2)
                elif vol != -1:
                    client.setvol(100)
            elif command == "vol down":
                vol = int(client.status()["volume"])
                if vol != -1 and vol > 1:
                    client.setvol(vol - 2)
                elif vol != -1:
                    client.setvol(0)
        except "ConnectionError":
            client.connect("localhost", 6600)
            dict[command]()
开发者ID:Giannie,项目名称:Pi_Time,代码行数:57,代码来源:mpd_lib.py

示例2: togglerandom

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
def togglerandom():
    client = MPDClient()
    client.connect("localhost", 6600)

    # Get status
    status = client.status()

    random = int(status['random'])
    if random == 1:
        client.random(0)
    else:
        client.random(1)

    client.close()
    client.disconnect()

    return jsonify(ok=True)
开发者ID:rawswift,项目名称:fmwc,代码行数:19,代码来源:app.py

示例3: __init__

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

示例4: __MPC

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

示例5: MPDClient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
uri = 'spotify:user:b584371:playlist:06nxCXR3zlRAxwqAz6FfaD'

client = MPDClient()

try:
    client.connect(host=HOST, port=PORT)
except SocketError:
    exit(1)

if PASSWORD:
    try:
        client.password(PASSWORD)
    except CommandError:
        exit(1)
client.clear()
client.random(1)
client.add(uri)
client.consume(0)
# client.crossfade(3)
# print(client.playlist())
client.play()
time.sleep(5)
'''
print(client.currentsong())
for x in range(1, 10):
    client.next()
    time.sleep(0.2)
    print(client.currentsong())
    time.sleep(5)
'''
开发者ID:bornhack,项目名称:baconfy,代码行数:32,代码来源:run.py

示例6: myMPD

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

#.........这里部分代码省略.........
                #                  "password commmand failed: %s" %
                #                  (self._host, e))
                #db.write_log_to_db_a(ac, "MPD-PW-Error: %s" % str(e), "x",
                #                             "write_also_to_console")
                return None

            # Catch all other possible errors
            except (MPDError, IOError) as e:
                #raise RunError("Could not connect to '%s': "
                #                  "error with password command: %s" %
                #                  (self._host, e))
                db.write_log_to_db_a(ac, "MPD-Error-2: %s" % str(e), "x",
                                             "write_also_to_console")
            return None

    def disconnect(self):
        # Try to tell MPD we're closing the connection first
        try:
            self._client.close()

        # If that fails, don't worry, just ignore it and disconnect
        except (MPDError, IOError):
            pass

        try:
            self._client.disconnect()

        # Disconnecting failed, so use a new client object instead
        # This should never happen.  If it does, something is seriously broken,
        # and the client object shouldn't be trusted to be re-used.
        except (MPDError, IOError):
            self._client = MPDClient()

    def exec_command(self, db, ac, command, value):
        """spread out exec commands"""
        result = None
        try:
            if command == "access":
                result = self.mpd_access(db, ac)
            if command == "play":
                result = self._client.play()
            if command == "update":
                result = self._client.update()
            if command == "song":
                result = self._client.currentsong()
            if command == "status":
                result = self._client.status()
            if command == "add":
                result = self._client.add(value)
            if command == "consume":
                result = self._client.consume(value)
            if command == "crossfade":
                result = self._client.crossfade(value)
            if command == "seek":
                result = self._client.seek(value)
            if command == "repeat":
                result = self._client.repeat(value)
            if command == "random":
                result = self._client.random(value)
            if command == "single":
                result = self._client.single(value)
            if command == "replay_gain_mode":
                result = self._client.replay_gain_mode(value)
            if command == "next":
                result = self._client.next()
            if command == "setvol":
                result = self._client.setvol(value)
            # via mpc-client
            if command == "crop":
                result = mpc_client(db, ac, "crop", value)
            if command == "vol":
                result = mpc_client(db, ac, "volume", value)
            # via os
            if command == "reload-1":
                result = run_cmd(db, ac, "killall", value)
            if command == "reload-2":
                result = run_cmd(db, ac, "mpd", value)
            return result

        # Couldn't get the current cmd, so try reconnecting and retrying
        except (MPDError, IOError) as e:
            # No error handling required here
            # Our disconnect function catches all exceptions, and therefore
            # should never raise any.
            error_msg = "MPD-Error-3: %s" % str(e)

            if value is not None:
                error_msg = error_msg + ", cmd: " + value
                #db.write_log_to_db_a(ac, "MPD-E-3 cmd-value: " + value, "x",
                #                             "write_also_to_console")
            if str(e) == "Not connected":
                error_msg = error_msg + ", try recon.:"
                db.write_log_to_db_a(ac, error_msg, "x",
                                                "write_also_to_console")
                self.connect(db, ac)
                self.exec_command(db, ac, command, value)
            else:
                db.write_log_to_db_a(ac, error_msg, "x",
                                                "write_also_to_console")
            return None
开发者ID:srb-fm,项目名称:admin-srb,代码行数:104,代码来源:lib_mpd.py

示例7: MPDClientDriver

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
class MPDClientDriver(Module):
    """MPD Client driver
    """
    _module_desc = ModuleArgument('mpd', 'MPD client-driver')
    _capabilities = [ModuleCapabilities.MultiInstanceAllowed]
    _required_kw = [ModuleArgument('address', 'server address'),
                    ModuleArgument('port', 'server port')]
    _optional_kw = [ModuleArgument('password', 'server password')]

    def __init__(self, **kwargs):
        super(MPDClientDriver, self).__init__(**kwargs)

        self.cli = MPDClient()

        # try to connect
        try:
            self.cli.connect(host=kwargs['address'],
                             port=kwargs['port'])
        except socket.error:
            raise MPDClientDriverLoadError('could not connect to server')

        if 'password' in kwargs:
            try:
                self.cli.password(kwargs['password'])
            except CommandError:
                raise MPDClientDriverLoadError('error while trying '
                                               'to input password')

        # disconnect
        self.cli.disconnect()

        # attach callbacks
        self.interrupt_handler(attach_manager_hook=['modman.tick',
                                                    [self._periodic_call,
                                                     MMHookAct.NO_ACTION,
                                                     self._registered_id]])

        self._automap_properties()
        self._automap_methods()

    def connect_mpd(fn):
        """Decorator function
           Connects to server, executes function and disconnects
        """
        def inner(self, *args, **kwargs):
            self._connect()
            ret = fn(self, *args, **kwargs)
            self.cli.disconnect()
            return ret
        return inner

    def catchsocketerror(fn):
        """Decorator
           Catches socket errors and logs them
        """
        def inner(self, *args, **kwargs):
            try:
                return fn(self, *args, **kwargs)
            except socket.error:
                self.interrupt_handler(log_error='could not connect '
                                       'to MPD server')

            return None

        return inner

    def _periodic_call(self, **kwargs):
        """Attached to module manager tick, send idle command?
        """
        pass

    @catchsocketerror
    def _get_random(self):
        """Returns random state
        """
        if self._read_status_key('random') == '0':
            return False
        else:
            return True

    @connect_mpd
    def _set_random(self, state):
        """Set random state
        """
        if state:
            self.cli.random(1)
        else:
            self.cli.random(0)

    @catchsocketerror
    def _get_repeat(self):
        """Returns repeat state
        """

        if self._read_status_key('repeat') == '0':
            return False
        else:
            return True

    @connect_mpd
#.........这里部分代码省略.........
开发者ID:brunosmmm,项目名称:aggregate,代码行数:103,代码来源:__init__.py

示例8: delete_event

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

#.........这里部分代码省略.........
                    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()


    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()
开发者ID:vincekd,项目名称:Pilaunch,代码行数:69,代码来源:pilaunch.py

示例9: Flask

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
from flask import Flask
app = Flask(__name__)
from app import views
from mpd import MPDClient

c = MPDClient()
c.timeout = 10
c.idletimeout = None
c.connect("localhost",6600)
c.random(0)
c.repeat(0)
c.consume(1)
#c.setvol(100)
c.close()   
开发者ID:ayypot,项目名称:ayydio,代码行数:16,代码来源:__init__.py

示例10: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
class player:
	def __init__(self,server):
		# Parameters
		if os.path.expanduser("~")<>"/root":
			self.config_dir = os.path.expanduser("~")+"/.dukebox/"
		else:
			# Nasty hack for running dukeboxd as root
			self.config_dir = "/home/pi/.dukebox/"
		self.server = server
		self.create_time = time.time()
		self.read_config()

		# Connect to MPD
		self.c = MPDClient()              
		self.c.timeout = 10
		self.c.idletimeout = None
		self.connect()
		
		status = self.c.status()
		if status.get("state")!="stop":
			temp = self.c.currentsong()
			self.genre = "All"
			self.last_genre = ""
			if status.get("random")=="1":
				print "+ Appear to be in track mode"
				self.mode = "track"
			else:
				self.mode = "album"
			# TODO - radio mode
			self.last_mode = ""
			self.last_song = temp.get("id")
			self.last_pos  = status.get("elapsed")
		else:		
			self.genre = "All"
			self.last_genre = ""
			self.mode = "album"
			self.last_mode = ""

		self.i=dict()
		self.n=dict()
		self.read_album_list()
		# List that changes depending on the genre selected
		self.some_albums = list(self.albums)
		# List of all albums that remains static for text search
		self.sort_albums = list(self.albums)
		self.album_art_stub = ""
		self.track_lengths = []
		
		seed()
		shuffle(self.albums)
		self.set_radio_stations()
		print "+ Music lists read: "+str(len(self.albums))+" local albums and "+str(len(self.radio_stations))+" radio stations."
		
		self.speak_lock = False


	def __del__(self):
		# Close the socket
		if self.connected:
			self.disconnect()
		
		
	def connect(self):
		print "+ Connecting to <"+self.server+">"
		try:
			self.c.connect(self.server, 6600)
			#print "+              ...connected"
			self.connected = True
			self.connected = True
			return True
		except:
			print "# Could not connect"
			self.connected = False
			return False
	
	
	def disconnect(self):
		print "+ Disconnecting from <"+self.server+">"
		self.c.close()
		self.c.disconnect()
			
		
	def read_config(self):
		# Defaults
		width = 1024
		height = 550
		self.fullscreen = False
		self.graphics = "simple"
		self.speak_option = "none"
		self.try_reading_battery = True
		self.screensaver_time = 30000
		
		# Read the Dukebox config file
		config_file = self.config_dir+"dukebox.conf"
		if os.path.isfile(config_file):
			for line in open(config_file):
				if line[0]!="#":
					try:
						if "width" in line:
							width = int(line.split("=")[-1].strip())
#.........这里部分代码省略.........
开发者ID:Bisxuit,项目名称:dukebox,代码行数:103,代码来源:dukebox_player.py

示例11: raspberry_explorer_board

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
def raspberry_explorer_board():

    logger = Logger().getLogger()
    config = Configuration()
    # Connect to MPD
    client = MPDClient() 
    client.connect("localhost", int(config.iniFile.get('mpd','port')))

    # Connect to NFC Explorer board
    logger.info('Connect to nxppy Mifare')
    mifare = nxppy.Mifare()

    # Initialize storage
    logger.info('Connect to Redis')
    storage = redis.StrictRedis(host='localhost', port=int(config.iniFile.get('redis','port')), db=0)

    # Count pauses to make sure it is not a error reading
    nbPause = 0
    # Keep previous uid to compare with current one
    previous_uid = None
    # Data from taf
    data = None

    if mifare is None:
        logger.info("Error while loading NFC Explorer Board")
    else:
        logger.info("Reader NFC Raspberry is now running")

        while True:
            try:
                uid = mifare.select()
                if uid is not None:
                    if uid == previous_uid:
                        nbPause = 0
                        if data:
                            status = client.status()
                            if status['state'] == 'stop':
                                logger.info("Play")
                                storage.set('current-tag-id', uid)
                                client.play(0)
                            if status['state'] == 'pause':
                                logger.info("Continue")
                                storage.set('current-tag-id', uid)
                                client.pause(0)
                        else:
                            pass
                    else:
                        previous_uid = uid

                        logger.info("New chip detected : %s" % uid)
                        # Save current-tag-id in memory to be used by services
                        storage.set('current-tag-id', uid)

                        # Stop mpd and 
                        client.stop()   
                        client.clear()

                        # Get from storage list of songs to play
                        tag = storage.get("tags:" + uid)

                        if tag is None:
                            logger.info("Unknown chip %s" % uid)
                            data = None
                        else:
                            # Load data
                            data = json.loads(tag)

                            logger.info(data)

                            # Configure MPD server
                            client.random(1 if data['random'] else 0)
                            client.repeat(1 if data['repeat'] else 0)

                            # Add songs
                            for song in data['songs']:
                                client.add(song)

                            if data['random']:
                                client.shuffle()

                            client.play(0)
                    
            except nxppy.SelectError:

                # Random error reading. Avoi
                if nbPause == 2:
                    nbPause = 0
                    # If play then 
                    if client.status()['state'] == 'play':
                        logger.info("Detect missing chip")
                        logger.info("Pause")
                        storage.delete('current-tag-id')
                        client.pause(1)
                    # If us
                    elif previous_uid and not data:
                        previous_uid = None
                        storage.delete('current-tag-id')
                else:
                    nbPause = nbPause + 1
            except Exception as e:
#.........这里部分代码省略.........
开发者ID:mpd-box,项目名称:mpd-box,代码行数:103,代码来源:raspberry_explorer_board.py

示例12: Controller

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
class Controller(object):
    class Mode:
        NONE = 0
        QUEUE = 1
        RANDOM = 2

    def __init__(self, host="/run/mpd/socket"):
        self.cli = MPDClient()
        self.cli.timeout = 10
        self.cli.idletimeout = None
        self.cli.connect(host, 0)
        log.info("Controller connected to MPD server version %s" % self.cli.mpd_version)

        self.mode = Controller.Mode.NONE
        self.switch_mode(Controller.Mode.RANDOM)

    def add_song(self, song):
        self.cli.add(song.as_mpd())

    def add_playlist(self, playlist):
        map(self.cli.add, playlist.as_mpd())

    def switch_mode(self, mode):
        self.mode = Controller.Mode.RANDOM

        if mode == Controller.Mode.RANDOM:
            self.cli.consume(0)
            self.cli.random(1)
            self.cli.repeat(1)
            self.cli.single(0)
            self.cli.clear()

            # Load up a ton of random songs
            playlist = Song.as_mpd_playlist(Song.select())
            map(self.cli.add, playlist)

        if mode == Controller.Mode.QUEUE:
            self.cli.consume(1)
            self.cli.random(0)
            self.cli.repeat(0)
            self.cli.single(0)
            self.cli.clear()

    def status(self):
      current_song = self.cli.currentsong()
      status = self.cli.status().items() + current_song.items()
      if 'title' in current_song:
          try:
              s = Song.get(Song.title == current_song['title'])
              status += s.to_dict().items()
          except Song.DoesNotExist: pass

      status = dict(status)
      status['playlist'] = self.cli.playlistinfo()
      return status

    def play(self):
      self.cli.play()

    def pause(self):
      self.cli.pause()

    def stop(self):
      self.cli.stop()

    def previous(self):
      self.cli.previous()

    def next(self):
      self.cli.next()


    def seek(self, ts):
      self.cli.seekcur(ts);
开发者ID:b1naryth1ef,项目名称:juicebox,代码行数:76,代码来源:controller.py

示例13: baconfyclient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import random [as 别名]
class baconfyclient(object):
    """docstring for  baconfyclient"""
    def __init__(self):
        super(baconfyclient, self).__init__()
        # self.arg = arg
        self.connect()

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

    def chunks(self, l, n):
        n = max(1, n)
        return [l[i:i + n] for i in range(0, len(l), n)]

    def pause(self):
        self.client.pause()

    def prev(self):
        self.client.previous()

    def init1337(self):
        self.connect()
        self.client.clear()
        self.client.add('spotify:user:b584371:playlist:4PaYAhJ2xibbm5q69yXgI7')
        #self.client.add('spotify:user:b584371:playlist:06nxCXR3zlRAxwqAz6FfaD')

    def playlist(self):
        playlist = self.client.playlist()
        playlistd = self.chunks(playlist,11)
        #pprint.pprint(playlistd)
        playlistan = {}
        for lista in playlistd:
            #print(lista)
            playlistan[str(lista[0]).strip(' ')] = {
                'file': str(lista[0]).strip(' '),
                'time': int(str(lista[1]).strip(' ')),
                'artist': str(lista[2]).strip(' '),
                'album': str(lista[3]).strip(' '),
                'title': str(lista[4]).strip(' '),
                'date': int(str(lista[5]).strip(' ')),
                'track': str(lista[6]).strip(' '),
                'pos': int(str(lista[7]).strip(' ')),
                'id': int(str(lista[8]).strip(' ')),
                'albumartist': str(lista[9]).strip(' '),
                'x-albumuri': str(lista[10]).strip(' '),
            }
            #print(type(lista))
            # file, time, artist, album, title, date, track, ppos, pid, albumartist, albumuri = map(lambda x: 11, lista)
            #print(map(lambda x: 11, lista))
        # pprint.pprint(playlistan)
        # print(json.dumps(playlist))
        return(playlistan)

    def next(self):
        self.client.next()

    def seek(self):
        return self.client.status()

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

    def percentage(self, part, whole):
        return 100 * float(part)/float(whole)

    def connect(self):
        self.client = MPDClient()

        try:
            self.client.connect(host=HOST, port=PORT)
        except SocketError:
            exit(1)

        if PASSWORD:
            try:
                self.client.password(PASSWORD)
            except CommandError:
                exit(1)
        self.client.consume(0)
        self.client.random(1)

    def sec2min(self, seconds):
        res = time.strftime('%M:%S', time.gmtime(int(seconds)))
        return res

    def currentsong(self):
        # print('test')
        songInfo = self.client.currentsong()
        status = self.client.status()
        # print(type(songInfo))
        # print(songInfo['time'])
        # return('Currently Playing: %s - %s [%s] (%s)' % (
        #     songInfo['artist'],
        #     songInfo['title'],
        #     self.sec2min(songInfo['time']),
        #     songInfo['album']
        # ))
        return {'song': songInfo, 'status': status}

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


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