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


Python MPDClient.repeat方法代码示例

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


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

示例1: togglerepeat

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

    # Get status
    status = client.status()

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

    client.close()
    client.disconnect()

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

示例2: __init__

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

示例3: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import repeat [as 别名]
class SoundClient:
    client = None

    def __init__(self, ident):
        from mpd import MPDClient
        # TODO fix this hack (this resolves circular deps
        self.port = MPD_START_PORT+ ident
        self.client = MPDClient()
        self.client.timeout = 10
        self.client.idletimeout = None

    def __enter__(self):
        self.client.connect('localhost', self.port)
        # normalize params again
        self.client.repeat(0)
        return self.client

    def __exit__(self, type, value, traceback):
        self.client.close()
        self.client.disconnect()
开发者ID:shackspace,项目名称:soundflower,代码行数:22,代码来源:mpdrunner.py

示例4: myMPD

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

示例5: MusicPlayer

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import repeat [as 别名]
class MusicPlayer(Action):
    """MusicPlayer for Alfred"""
    def __init__(self, cfg):
        super(MusicPlayer, self).__init__(cfg)
        self.triggers = ["music","audio"]
        self.mpd = MPDClient()
        self.mpd.connect("localhost", "6600")
        self.mpd.consume(0)

    def _do_update(self, command):
        self.mpd.update()

    def _do_list(self, command):
        llista = self.mpd.list('file')
        print llista
        if len(llista) > 0:
            return "\n".join(llista)
        else:
            return "Empty List SIR"

    def _do_add(self, command):
        song = " ".join(command[1:])
        self.mpd.add(song)
        return "Song %s Added SIR" % (song)

    def _do_queue(self,command):
        return "list: %s" % (self.mpd.playlist())

    def _do_clear(self, command):
        self.mpd.clear()
        return "Clear Done SIR"

    def _do_next(self, command):
        self.mpd.next()
        return "Next Song Done SIR"

    def _do_previous(self, command):
        self.mpd.previous()
        return "Previous Song Done SIR"

    def _do_pause(self, command):
        self.mpd.pause()
        return "Music Paused SIR"

    def _do_shuffle(self, command):
        self.mpd.shuffle()
        return "Music shuffled SIR"

    def _do_repeat(self, command):
        try:
            if command[1] == "on":
                self.mpd.repeat(1)
                return "Repeat Set On SIR"
            elif command[1] == "off":
                self.mpd.repeat(0)
                return "Repeat Set Off SIR"
            else:
                return "Error SIR"
        except:
            return "Error SIR"

    def _do_play(self, command):
        try:
            songpos = command[1]
            self.mpd.play(int(songpos))
            return "Playing %s Song Done SIR" % (songpos)
        except:
            self.mpd.play()
            return "Music Playing SIR"

    def _do_stop(self, command):
        self.mpd.stop()
        return "Music Stoped SIR"

    def do(self, command):
        print "Will", " ".join(command), "music"
        print command
        if command[0] == "update":
            self._do_update(command)
        elif command[0] == "list":
            return self._do_list(command)
        elif command[0] == "add":
            return self._do_add(command)
        elif command[0] == "queue":
            return self._do_queue(command)
        elif command[0] == "play":
            return self._do_play(command)
        elif command[0] == "stop":
            return self._do_stop(command)
        elif command[0] == "clear":
            return self._do_clear(command)
        elif command[0] == "next":
            return self._do_next(command)
        elif command[0] == "previous":
            return self._do_previous(command)
        elif command[0] == "pause":
            return self._do_pause(command)
        elif command[0] == "repeat":
            return self._do_repeat(command)
        elif command[0] == "shuffle":
#.........这里部分代码省略.........
开发者ID:Costar93,项目名称:Alfred,代码行数:103,代码来源:MusicPlayer.py

示例6: MPDClientDriver

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

示例7: delete_event

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

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


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

示例8: Flask

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

示例9: raspberry_explorer_board

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

示例10: Controller

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

示例11: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import repeat [as 别名]
class RadioPlayer:
    def __init__(self, announce, specialUrl=None, specialDescription=None):
        self.announce = announce
        self.currentStationName = None
        self.playCount = 0
        self.specialUrl = specialUrl
        self.specialDescription = specialDescription
        self.specialNext = True
        self.lock = threading.Lock()
        self.mpdClient = MPDClient()
        self.mpdClient.connect("localhost", 6600)
        self.mpdClient.repeat(1)
        self.mpdClient.stop()
        self.mpdClient.clear()
        self.mpdClient.disconnect()


    def nextStation(self):
        if self.playCount < 1:
            if self.specialUrl is not None and self.specialNext:
                self.playUrl(self.specialUrl, self.specialDescription)
                self.playCount += 1
                self.specialNext = False
            else:
                self.playStation(streams.getRandomStation())
                self.playCount += 1
                self.specialNext = True
        else:
            self.stopPlaying()
            self.playCount = 0


    def playStation(self, stationName):
        self.playUrl(streams.getStream(stationName), streams.getDescription(stationName))


    def playUrl(self, url, description):
        self.lock.acquire()
        try:
            if self.currentStationName is not None:
                self.__stop__()

            self.mpdClient.connect("localhost", 6600)
            self.mpdClient.add(url)

            time.sleep(0.2)
            self.announce(description)

            self.mpdClient.play()
            self.mpdClient.disconnect()

            self.currentStationName = description
        finally:
            self.lock.release()


    def stopPlaying(self):
        self.lock.acquire()
        try:
            self.__stop__()
            time.sleep(0.2)
            self.announce("Stopped")
        finally:
            self.lock.release()


    def __stop__(self):
        self.mpdClient.connect("localhost", 6600)
        self.mpdClient.stop()
        self.mpdClient.clear()
        self.mpdClient.disconnect()
        self.currentStationName = None
        self.playCount = 0
开发者ID:101100,项目名称:radiopi,代码行数:75,代码来源:player.py


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