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


Python MPDClient.previous方法代码示例

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


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

示例1: main

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import previous [as 别名]
def main():
    print "Content-Type: application/json\n"
    client = MPDClient()
    if not mpdConnect(client, CON_ID):
        print '{ "status": "failure", "message": "failed to connect to MPD server. '+HOST+':'+PORT+'"}'
        sys.exit(-1)

    if PASSWORD != '':
        if not mpdAuth(client, PASSWORD):
            print '{ "status": "failure", "message": "failed to auth against MPD server."}'
            sys.exit(-1)

    command = os.environ['SCRIPT_NAME'].replace('/mpd/control/', '')

    try:
        if command == 'pause/':
            client.pause()
            print '{ "status": "success" }'
        elif command == 'play/':
            client.play()
            print '{ "status": "success" }'
        elif command == 'next/':
            client.next()
            print '{ "status": "success" }'
        elif command == 'previous/':
            client.previous()
            print '{ "status": "success" }'
    except CommandError:
        print '{ "status": "failure", "message": "unknown command" }'
开发者ID:pcon,项目名称:mpd-rest,代码行数:31,代码来源:mpd-ctrl.py

示例2: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import previous [as 别名]
class Player:
	def __init__(self):
	    self.client = MPDClient()
	    self.client.connect("localhost", 6600)
	    self.client.timeout = 10
	    self.client.idletimeout = None


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

	def get_playlists(self):
	    val = self.client.listplaylists()
	    return val

	def get_stats(self):
		#{'playtime': '848', 'uptime': '2565'}
		#{'songid': '33', 'playlistlength': '1', 'playlist': '86', 'repeat': '0',
		#'consume': '0', 'mixrampdb': '0.000000', 'random': '0', 'state': 'play',
		# 'elapsed': '7.476', 'volume': '-1', 'single': '0', 'time': '7:0', 'song': '0', 'audio': '44100:16:2', 'bitrate': '128'}
		all = {}
		all.update(self.client.stats())
		all.update(self.client.status())

		stats = {}
		stats["elapsed"] = all["elapsed"] if all.has_key("elapsed") else "0"
		stats["state"] = all["state"] if all.has_key("state") else "stopped"
		stats["playtime"] = all["playtime"]
		stats["uptime"] = all["uptime"]
		stats["bitrate"] = all["bitrate"] if all.has_key('bitrate') else 0
		stats["playlistlength"] = all["playlistlength"] if all.has_key("playlistlength") else 0
		stats["song"] = all["song"] if all.has_key("song") else 0
		# print stats
		return stats

	def get_playing(self):
		name = "unknown"
		val = self.client.currentsong()
		name= val["name"] if val.has_key('name') else None
		name= val["title"] if val.has_key('title') else name
		# print val
		return name

	def load(self, list):
		# print "loading list", list
		self.client.clear()
		self.client.load(list)

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

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

	def stop(self):
		self.client.stop()
开发者ID:alexellis,项目名称:pyPlaylist,代码行数:61,代码来源:mpc.py

示例3: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import previous [as 别名]
class MPDCli:
    def __init__(self, ipaddress):
        self.client = MPDClient()
        self.client.timeout = 10
        self.client.idletimeout = None
        self.client.connect(ipaddress, 6600)
        self.client.consume(0)

        self.ip = ipaddress

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

    def __tryConnect(self):
        try:
            self.client.update()
        except ConnectionError:
            self.client.connect(self.ip, 6600)
            self.client.update()

    def getNowPlaying(self):
        self.__tryConnect()
        return self.client.currentsong()

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

    def play(self):
        self.__tryConnect()

        currentState = self.client.status()['state']

        if currentState == 'stop':
            self.client.play(int(self.client.status()['song']))
        else:
            self.client.pause()

        return self.client.status()

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

    def prev(self):
        self.__tryConnect()
        self.client.previous()
        return self.client.status()

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

    def idle(self):
        self.__tryConnect()
        self.client.idle()
开发者ID:mikdsouza,项目名称:PyPiMPD,代码行数:61,代码来源:MPDC.py

示例4: __init__

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

示例5: previous

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

    # Previous track
    client.previous()

    client.close()
    client.disconnect()

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

示例6: main

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import previous [as 别名]
def main():
    ## MPD object instance
    client = MPDClient()
    mpdConnect(client, CON_ID)

    status = client.status()
    print status

    timebuttonisstillpressed = 0

    flashLED(0.1, 5)
    updateLED(client)

    while True:
        try:
            device = checkForUSBDevice("1GB") # 1GB is the name of my thumb drive
            if device != "":
                # USB thumb drive has been inserted, new music will be copied
                flashLED(0.1, 5)
                client.disconnect()
                loadMusic(client, CON_ID, device)
                mpdConnect(client, CON_ID)
                print client.status()
                flashLED(0.1, 5)
                # wait until thumb drive is umplugged again
                while checkForUSBDevice("1GB") == device:
                        sleep(1.0)
                flashLED(0.1, 5)
            if GPIO.input(BUTTON) == True:
                if timebuttonisstillpressed == 0:
                    # button has been pressed, pause or unpause now
                    if client.status()["state"] == "stop":
                        client.play()
                    else:
                        client.pause()
                    updateLED(client)
                elif timebuttonisstillpressed > 4:
                    # go back one track if button is pressed > 4 secs
                    client.previous()
                    flashLED(0.1, 5)
                    timebuttonisstillpressed = 0
                timebuttonisstillpressed = timebuttonisstillpressed + 0.1
            else:
                timebuttonisstillpressed = 0

            sleep(0.1)
            log_message("foobar")
        except Exception as e:
            log_message(e.message)
开发者ID:AndreasSoiron,项目名称:theonebuttonaudiobookplayer,代码行数:51,代码来源:tobabp.py

示例7: MyMPDClient

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

示例8: Player

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import previous [as 别名]
class Player():
    """ Main class. Supports communicating with MPD """

    connected_to_mpd = False
    currentLetterNumber = 0
    maxLetterNumber = 0

    def __init__(self):
        """ Coonects to MPD, prints version """
        self.client = MPDClient()               # create client object
#        self.client.timeout = 10                # network timeout in seconds (floats allowed), default: None
#        self.client.idletimeout = None          # timeout for fetching the result of the idle command is handled seperately, default: None

        self.MPDserverconnect()
        self.mixer = alsaaudio.Mixer(control='PCM', id=0, cardindex=1)

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


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


    def MPDserverconnect(self):
        try:
            self.client.connect("localhost", 6600)  # connect to piplay:6600
            print 'MPD version',
            print(self.client.mpd_version)          # print the MPD version
            self.connected_to_mpd = True
        except:
            self.connected_to_mpd = False


    def MPDserverDisconnect(self):
        for i in xrange(5):
            try:
                self.client.close()                     # send the close command
                self.client.disconnect()                # disconnect from the server
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


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


    def MPDupdateDatabase(self):
        """ Updates MPD's music database """
        for i in xrange(5):
            try:
                self.client.update()
                print('Updating music database...')
                while 'updating_db' in self.client.status():
                    sleep(1)
                print('Done!')
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDclearPlayList(self):
        for i in xrange(5):
            try:
                self.client.clear()
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
#.........这里部分代码省略.........
开发者ID:OSliusarenko,项目名称:yaih,代码行数:103,代码来源:player2.py

示例9: OBABP

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

#.........这里部分代码省略.........
    def satupGPIO(self, mode):
#        GPIO.cleanup();
        GPIO.setmode(mode);
        GPIO.setup(self.led, GPIO.OUT);
        GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        
    
    def flashLED(self, speed, time):
        for x in range(0, time):
            GPIO.output(self.led, GPIO.LOW)
            sleep(speed)
            GPIO.output(self.led, GPIO.HIGH)
            sleep(speed)
    
    def loadMusic(self, device):
        os.system("mount "+device+" "+self.mountPoint);
        os.system("/etc/init.d/mpd stop");
        os.system("rm "+self.musicDir+"*");
        os.system("cp "+self.mountPoint+"* "+self.musicDir);
        os.system("umount "+self.mountPoint);
        os.system("rm "+self.mpdTagCasche);
        os.system("/etc/init.d/mpd start")
        os.system("mpc clear")
        os.system("mpc ls | mpc add")
        os.system("/etc/init.d/mpd restart")
    
    def updateLED(self):
        # adjust LED to actual state
        if self.client.status()["state"] == "play":
            GPIO.output(self.led, GPIO.LOW)
        else:
            GPIO.output(self.led, GPIO.HIGH)


    def checkForUSBDevice(self):
        res = ""
        context = pyudev.Context()
        for device in context.list_devices(subsystem='block', DEVTYPE='partition'):
                if device.get('ID_FS_LABEL') == self.driveName:
                        res = device.device_node
        return res
    
    def buttonDown(self):
        if GPIO.input(self.button) == False:
            return True;
        else:
            return False;
    def playPause(self):
        print "play/pause"
        if self.client.status()["state"] == "stop":
            self.client.play();
        else:
            self.client.pause();
    
    
    def go(self):
        self.connectMPD()
       
        
        print self.client.status();

        timebuttonisstillpressed = 0
        
        self.flashLED(0.1, 10);
        self.updateLED();
        print "setup ok"
        while True:
            pendrive = self.checkForUSBDevice();
            self.updateLED();
            if pendrive != "":
                print "new music detected"
                self.flashLED(0.1, 5);
                self.client.disconnect();
                self.loadMusic(pendrive);
                self.connectMPD();
                print self.client.status();
                self.flashLED(0.05, 10)
                while self.checkForUSBDevice() == pendrive:
                    self.flashLED(0.1, 1);
                    sleep(0.1);
                print "new music added"
                self.flashLED(0.1, 5);
            if self.buttonDown():
                if timebuttonisstillpressed == 0:
                    self.playPause();
                    sleep(0.1)
                    self.updateLED();
                if timebuttonisstillpressed > 4:
                    print "prev"
                    self.client.previous();
                    self.flashLED(0.1, 5);
                    timebuttonisstillpressed = 0;
                timebuttonisstillpressed = timebuttonisstillpressed + 0.1;
            else:
                timebuttonisstillpressed = 0;
            
            sleep(0.1)
        
        return 1;
开发者ID:dangraves,项目名称:RPi-OBABP,代码行数:104,代码来源:OBABP.py

示例10: __MPC

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

示例11: Mpd

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

#.........这里部分代码省略.........
        try:
            self.client.disconnect()
        except Exception:
            self.log.exception('Error disconnecting mpd')
            return False
        self.connected = False
        return True

    def mpdAuth(self, secret):
        """
            Authenticate
        """
        try:
            self.client.password(secret)
        except CommandError:
            return False
        return True

    def _configure(self, qtile, bar):
        base._Widget._configure(self, qtile, bar)
        self.layout = self.drawer.textlayout(
            self.text, self.foreground, self.font, self.fontsize,
            markup=True)
        self.timeout_add(1, self.update)
        atexit.register(self.mpdDisconnect)

    def update(self):
        if self.connect(True):
            try:
                status = self.client.status()
                song = self.client.currentsong()
                volume = status.get('volume', '-1')
                if song:
                    artist = ''
                    title = ''
                    if 'artist' in song:
                        artist = song['artist'].decode('utf-8')
                    if 'title' in song:
                        title = song['title'].decode('utf-8')

                    if 'artist' not in song and 'title' not in song:
                        playing = song.get('file', '??')
                    else:
                        playing = u'%s − %s' % (artist, title)

                    if status and status.get('time', None):
                        elapsed, total = status['time'].split(':')
                        percent = float(elapsed) / float(total)
                        progress = int(percent * len(playing))
                        playing = '<span color="%s">%s</span>%s' % (
                            utils.hex(self.foreground_progress),
                            utils.escape(playing[:progress].encode('utf-8')),
                            utils.escape(playing[progress:].encode('utf-8')))
                    else:
                        playing = utils.escape(playing)
                else:
                    playing = 'Stopped'

                playing = '%s [%s%%]' % (playing,
                                         volume if volume != '-1' else '?')
            except Exception:
                self.log.exception('Mpd error on update')
                playing = self.msg_nc
                self.mpdDisconnect()
        else:
            if self.reconnect:
                playing = self.msg_nc
            else:
                return False

        if self.text != playing:
            self.text = playing
            self.bar.draw()

        return True

    def click(self, x, y, button):
        if not self.connect(True):
            return False
        try:
            status = self.client.status()
            if button == 3:
                if not status:
                    self.client.play()
                else:
                    self.client.pause()
            elif button == 4:
                self.client.previous()
            elif button == 5:
                self.client.next()
            elif button == 8:
                if status:
                    self.client.setvol(
                        max(int(status['volume']) - self.inc, 0))
            elif button == 9:
                if status:
                    self.client.setvol(
                        min(int(status['volume']) + self.inc, 100))
        except Exception:
            self.log.exception('Mpd error on click')
开发者ID:Cadair,项目名称:qtile,代码行数:104,代码来源:mpdwidget.py

示例12: MPDClientDriver

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

#.........这里部分代码省略.........
            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
    def _set_repeat(self, state):
        """Set repeat state
        """
        if state:
            self.cli.repeat(1)
        else:
            self.cli.repeat(0)

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

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

    @catchsocketerror
    def _get_volume(self):
        """Returns volume
        """
        return self._read_status_key('volume')

    @connect_mpd
    def _set_volume(self, value):
        """Set volume
        """
        self.cli.volume(value)

    @catchsocketerror
    def _get_state(self):
        """Get current state
        """
        return self._read_status_key('state')

    @connect_mpd
    def _next(self):
        """Next song
        """
        self.cli.next()

    @connect_mpd
    def _previous(self):
        """Previous song
        """
        self.cli.previous()

    @connect_mpd
    def _stop(self):
        """Stop playback
        """
        self.cli.stop()

    @connect_mpd
    def _pause(self, resume):
        """Pause / resume
        """
        if resume:
            self.cli.pause(1)
        else:
            self.cli.pause(0)

    def _connect(self):
        """Connect to MPD server
        """
        self.cli.connect(host=self._loaded_kwargs['address'],
                         port=self._loaded_kwargs['port'])

    def _read_status_key(self, key_name):
        """Get some status
        """
        try:
            self._connect()
            ret = self.cli.status()[key_name]
        finally:
            self.cli.disconnect()

        return ret
开发者ID:brunosmmm,项目名称:aggregate,代码行数:104,代码来源:__init__.py

示例13: Mpd

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

#.........这里部分代码省略.........

    def get_volume(self):
        return self.status['volume']

    def get_single(self):
        if self.status['single'] == '1':
            return '1'
        else:
            return '_'

    def get_repeat(self):
        if self.status['repeat'] == '1':
            return 'R'
        else:
            return '_'

    def get_shuffle(self):
        if self.status['random'] == '1':
            return 'S'
        else:
            return '_'

    formats = {'a': get_artist, 'A': get_album, 'e': get_elapsed, 
               'f': get_file, 'l': get_length, 'n': get_number, 
               'p': get_playlistlength, 's': get_status, 'S': get_longstatus, 
               't': get_title, 'T': get_track, 'v': get_volume, '1': get_single,
               'r': get_repeat, 'h': get_shuffle, '%': lambda x: '%', }

    def match_check(self, m):
        try:
            return self.formats[m.group(1)](self)
        except KeyError:
            return "(nil)"

    def do_format(self, string):
        return re.sub("%(.)", self.match_check, string)

    def update(self):
        if not self.configured:
            return True
        if self.connect(True):
            try:
                self.status = self.client.status()
                self.song = self.client.currentsong()
                if self.status['state'] != 'stop':
                    playing = self.do_format(self.fmt_playing)

                    if self.do_color_progress and self.status and self.status.get('time', None):
                        elapsed, total = self.status['time'].split(':')
                        percent = float(elapsed) / float(total)
                        progress = int(percent * len(playing))
                        playing = '<span color="%s">%s</span>%s' % (
                            utils.hex(self.foreground_progress),
                            utils.escape(playing[:progress]),
                            utils.escape(playing[progress:]))
                    else:
                        playing = utils.escape(playing)
                else:
                    playing = self.do_format(self.fmt_stopped)

            except Exception:
                self.log.exception('Mpd error on update')
                playing = self.msg_nc
                self.mpdDisconnect()
        else:
            if self.reconnect:
                playing = self.msg_nc
            else:
                return False

        if self.text != playing:
            self.text = playing
            self.bar.draw()

        return True

    def button_press(self, x, y, button):
        if not self.connect(True):
            return False
        try:
            status = self.client.status()
            if button == 3:
                if not status:
                    self.client.play()
                else:
                    self.client.pause()
            elif button == 4:
                self.client.previous()
            elif button == 5:
                self.client.next()
            elif button == 8:
                if status:
                    self.client.setvol(
                        max(int(status['volume']) - self.inc, 0))
            elif button == 9:
                if status:
                    self.client.setvol(
                        min(int(status['volume']) + self.inc, 100))
        except Exception:
            self.log.exception('Mpd error on click')
开发者ID:Echota,项目名称:qtile,代码行数:104,代码来源:mpdwidget.py

示例14: Controller

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

示例15: Player

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import previous [as 别名]
class Player(object):
    UNKNOWN = 0  # state
    PAUSE = 1  # state
    PLAY = 2  # state
    STOP = 3  # state

    HOST = 'localhost'
    PORT = '6600'

    def __init__(self, green, red):
        self.green = green
        self.red = red
        self.mpdClient = None
        self.__ensureConnected()

    def __ensureConnected(self):
        while self.__isConnected() is False:
            try:
                print("Connecting to MPD ...")
                self.mpdClient = MPDClient()
                self.mpdClient.connect(
                    host=self.HOST, port=self.PORT)
                print("Connected. ")
            except (ConnectionError, ConnectionRefusedError):
                print("Could not connect to MPD. Retrying ...")
                self.red.flash(.2, 1)
                sleep(.5)

    def __isConnected(self):
        if self.mpdClient is None:
            return False
        try:
            self.mpdClient.ping()
        except (ConnectionError, BrokenPipeError):
            return False
        return True

    @property
    def state(self):
        self.__ensureConnected()
        state = self.mpdClient.status()["state"]
        if state == "pause":
            return self.PAUSE
        elif state == "play":
            return self.PLAY
        elif state == "stop":
            return self.STOP
        return self.UNKNOWN

    def play(self):
        self.__ensureConnected()
        while self.state is not self.PLAY:
            self.mpdClient.play()
            sleep(.1)
        self.green.on()

    def pause(self):
        self.__ensureConnected()
        self.mpdClient.pause()
        self.green.off()

    def track_back(self):
        self.__ensureConnected()
        self.mpdClient.previous()
        self.green.flash(.2, 3,
                         turnOn=True if self.state is self.PLAY else False)
开发者ID:rpoisel,项目名称:onebutton,代码行数:68,代码来源:player.py


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