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


Python MPDClient.idle方法代码示例

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


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

示例1: __init__

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

示例2: _mopidy_idle

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import idle [as 别名]
    def _mopidy_idle(self):
        client_idle = MPDClient()
        client_idle.connect(MOPIDY_HOST, MOPIDY_PORT)
        while client_idle.status()['state'] != "stop":
            client_idle.idle()

        client_idle.close()
        client_idle.disconnect()
开发者ID:cthit,项目名称:playIT-grails,代码行数:10,代码来源:playIT_client.py

示例3: Observer

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import idle [as 别名]
class Observer(QThread):
    """MPD Observer thread."""
    def __init__(self):
        self._config = ServiceLocator.getGlobalServiceInstance(ServiceNames.Configuration)
        self.client = MPDClient()

        return QThread.__init__(self)

    def __del__(self):
        self.wait()

    def mpdConnect(self):
        self.client.timeout = 10
        self.client.idletimeout = None
        self.client.connect(self._config.mpdserver, self._config.mpdport)
        if len(self._config.mpdpassword) > 0:
            self.client.password(self._config.mpdpassword)
        self.client.update()

    def run(self):
        try:
            self.mpdConnect()
    
            while True:
                info = self.client.idle()
                print("info:{0}".format(info))
                if 'update' in info:
                    # Update all
                    self.updatePlaylist()
                    self.updatePlayer()
                    self.updateMixer()

                if 'playlist' in info:
                    self.updatePlaylist()
                if 'player' in info:
                    self.updatePlayer()
                    self.updateMixer()
                if 'mixer' in info:
                    self.updateMixer()
                self.sleep(2)
        except:
             self.emit(SIGNAL(ObserverSignals.ConnectionError))
            

        pass

    def updatePlaylist(self):
        playlist = self.client.playlistinfo()
        self.emit(SIGNAL(ObserverSignals.PlaylistChanged), playlist)
        pass
    def updateMixer(self):
        status = self.client.status()
        self.emit(SIGNAL(ObserverSignals.MixerChanged), status)
        pass

    def updatePlayer(self):
        currentSong = self.client.currentsong()
        self.emit(SIGNAL(ObserverSignals.PlayerChanged), currentSong)
        pass
开发者ID:huvermann,项目名称:CuteMpd,代码行数:61,代码来源:Observer.py

示例4: onjoined

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import idle [as 别名]
def onjoined():
    print("session joined")

    while True:
        ######################
        # Publish to the topic

        client = MPDClient()
        client.connect("localhost", 6600)
        client.use_unicode = True
        event = client.idle()
        yield app.session.publish('radio.event', event)
        client.close()
        print(event)
        yield sleep(0.5)
开发者ID:crazyiop,项目名称:hipsterRadio,代码行数:17,代码来源:mpdevent.py

示例5: MPDThread

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import idle [as 别名]
class MPDThread(Thread):
    def __init__(self,mpdhost,mpdport,logger):
        super(MPDThread,self).__init__(logger)
        self.mpd = MPDClient()
        self.host = mpdhost
        self.port = mpdport
        
    def run(self):
        try:
            self.mpd.connect(self.host,self.port)
            while self.iterate():
                self.subsys = self.mpd.idle()
                self.set_data(self.subsys)
            self.mpd.disconnect()
        except MPDError, e:
            self.logger.debug('%s' % str(e))
开发者ID:jmechnich,项目名称:musicpi_lcd,代码行数:18,代码来源:printer_mpd.py

示例6: add_weather_tracks

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import idle [as 别名]
    return [status['song'],status['playlistlength']]

def add_weather_tracks(client):
    client.add('tts.mp3')
#    client.add('tts.mp3')

def move_weather_tracks(client):
    current = current_track(client)
    client.move(int(current[1])-1,current[0])
#    client.move(int(current[1])-1,current[0])


add_weather_tracks(client)
move_weather_tracks(client)
client.setvol(90)
client.random(0)
current = current_track(client)
texttospeech.speakSpeechFromText(forecast.full_report1)
client.play(int(current[0])-1)
client.idle()
client.idle()
client.pause()
texttospeech.speakSpeechFromText(forecast.full_report2)
client.previous()
client.idle()
client.idle()
client.setvol(85)
client.random(1)

client.close()
client.disconnect()
开发者ID:Giannie,项目名称:LCD_Alarm_Pi,代码行数:33,代码来源:weather.py

示例7: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import idle [as 别名]
class BotHelper:
    def __init__(self, sensors, rrd, log_path,mpd_event,hub_ctrl = None, mpd_host='localhost',mpd_port='6600'):
        self.sensors = sensors
        self.worker_thread_mpd = None
        self.running_thread = False
        self.started = False
        self.rrd = rrd
        self.hub_ctrl = hub_ctrl
        self.mpd_event = mpd_event
        self.mpd_client = MPDClient()               # create client object
        self.mpd_client.timeout = 10                # network timeout in seconds (floats allowed), default: None
        self.mpd_client.idletimeout = None          # timeout for fetching the result of the idle command is handled seperately, default: None
        self.mpd_client.connect(mpd_host, mpd_port)  # connect to localhost:6600

        # logging config
        logging.basicConfig(level=logging.ERROR)
        pp = pprint.PrettyPrinter(indent=4)
        formatter = logging.Formatter('%(asctime)s %(message)s')
        logger = logging.getLogger('')
        logger.setLevel(logging.INFO)

        fh = logging.FileHandler(log_path)
        fh.setLevel(logging.INFO)
        fh.setFormatter(formatter)
        logger.addHandler(fh)

        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        ch.setFormatter(formatter)
        logger.addHandler(ch)
        logger.info("Init")


    def get_mpd_state(self):
        #return self.mpd_client.status()
        pass

    def mpd_worker(self):
        self.running_thread = True
        logging.info("===Starting thread for mpd status listener===")
        last_state = None
        self.off = False
        self.just_off = False
        while self.running_thread:
            self.mpd_client.idle()
            logging.info("===Waiting thread mpd status===")
            status = self.mpd_client.status()
            logging.info("===Status event in thread mpd===")
            state = status['state']

            print str(status)
            logging.info("Music change state: "+str(status['state']) + " last state: "+str(last_state))
            result = self.sensors.active_sound_detector

            if state =='play' and last_state!='play' and last_state!=None:
                result = self.sensors.detect_sound(True)

            if state =='stop' and last_state!='stop' and last_state!=None:
                result = self.sensors.detect_sound(False)
                # usb ports off (audio usb)
                if self.hub_ctrl != None:
                    self.mpd_client.disableoutput(0)
                    time.sleep(2)
                    self.power_off_usbs();
                    logging.info("Power off usbs")
                    self.off=True
                    # since we disabled output mpd_cliend.idle will issue new event with status stop again
                    self.just_off = True

            # usb ports on (audio usb)
            if state =='stop' and last_state=='stop':
                if self.just_off:
                    # just power off consuming dsiableoutput event
                    self.just_off = False;
                elif self.off and self.hub_ctrl != None:
                    # if this is a play command it will not work since power is off but will poweron usb for next command
                    self.power_on_usbs();
                    logging.info("Power on usbs")
                    self.off = False
                    time.sleep(2)
                    self.mpd_client.enableoutput(0)

            last_state = state
            if hasattr(self,'mpd_event'):
                self.mpd_event(result);
        logging.info("===Ending thread for mpd status listener===\n")

    def run(self):
        if not self.started:
            self.sensors.detect_all(True)
            self.worker_thread_mpd = threading.Thread(target=self.mpd_worker)
            self.worker_thread_mpd.start()
            self.started = True
            return True;
        else:
            return False;

    def stop(self):
        if self.started:
            self.sensors.detect_all(False)
#.........这里部分代码省略.........
开发者ID:Jacq,项目名称:RaspberryBot,代码行数:103,代码来源:helpers.py

示例8: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import idle [as 别名]
class Music:
    def __init__(self, hostname="localhost", port="6600", password=None):
        self.hostname = hostname
        self.port = port
        self.password = password
        self.mpd = None

    def clone(self):
        return Music(self.hostname, self.port, self.password)

    def connect(self):
        if self.mpd:
            # the mpd client library is very buggy, too lazy to fix it,
            # so making an ugly hack.
            try:
                self.mpd.disconnect()
            except:
                pass
            finally:
                self.mpd = None

        self.mpd = MPDClient()

        self.mpd.connect(self.hostname, self.port)
        if self.password:
            self.mpd.password(self.password)

    def render(self):
        status = self.mpd.status()
        song = self.mpd.currentsong()
        info = PanelStrip("music")

        if status["state"] not in ("play", "pause"):
            return info.text("DON'T PANIC!")

        info.icon("music")
        info += PanelStrip().text(song["artist"]).trim(200).text(" - ")

        if status["state"] == "play":
            colour = PanelVisual.active
        else:
            colour = None
        info += PanelStrip().text(song["title"], colour).trim(200)
        info.move(8).icon("volume").move(3)
        return info.text(status["volume"])

    def safe_call(self, method, *args, **kwargs):
        try:
            return getattr(self.mpd, method)(*args, **kwargs)
        except (MPDError, ConnectionError, AttributeError):
            self.connect()
            return getattr(self.mpd, method)(*args, **kwargs)

    def play(self):
        return self.safe_call("play")

    def pause(self):
        return self.safe_call("pause")

    def stop(self):
        return self.safe_call("stop")

    def seek(self, position):
        return self.safe_call("seekcur", position)

    def next(self):
        return self.safe_call("next")

    def previous(self):
        return self.safe_call("previous")

    def volume(self, volume, relative=False):
        if relative:
            old_volume = int(self.safe_call("status")["volume"])
            return self.safe_call("setvol", old_volume + volume)
        else:
            return self.safe_call("setvol", volume)

    def loop(self, events):
        while True:
            try:
                self.connect()
                while True:
                    events.put(self.render())
                    self.mpd.idle()
            except MPDError:
                print(sys.exc_info())
                events.put(PanelStrip("music").text("PANIC!!!"))
                sleep(20)
开发者ID:DexterLB,项目名称:ui,代码行数:91,代码来源:music.py

示例9: Ajax

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

#.........这里部分代码省略.........
            return "Unknown output"
        self.mpd_connect()
        self.client.enableoutput(i)
        return "Output enabled"

    def ajax_mpd_disableoutput(self, args):
        try:
            i = int(args.get('i'))
        except ValueError:
            return "Unknown output"
        if i < 0:
            return "Unknown output"
        self.mpd_connect()
        self.client.disableoutput(i)
        return "Output disabled"

    def ajax_html_playlist(self, args):
        self.mpd_connect()
        pl = self.client.playlistinfo()
        map(self.fix_pl, pl)

        status = self.client.status()
        if 'song' not in status:
            status['song'] = -1
        mpd_status = 'unknown'
        if status['state'] == 'play':
            mpd_status = 'playing song %d' % (int(status['song']) + 1)
        if status['state'] == 'stop':
            mpd_status = 'stopped'
        if status['state'] == 'pause':
            mpd_status = 'paused'
        return render_template('playlist.html', pl=pl, mpd_status=mpd_status, song=status['song'])

    def ajax_html_streams(self, args):
        return render_template('streams.html', streams=self.config['streams'])

    def ajax_html_outputs(self, args):
        self.mpd_connect()
        outputs = self.client.outputs()
        return render_template('outputs.html', outputs=outputs)

    def ajax_json_mpd_idle(self, args):
        self.mpd_connect()
        #idle = self.client.idle('playlist')
        idle = self.client.idle()
        return json.dumps(idle)

    def serve_file(self, fileid):
        sql = select([self.db_songtable], self.db_songtable.c.id == fileid)
        rows = self.dbc.execute(sql).fetchall()
        if len(rows):
            row=rows[0]
            fname = os.path.join(row['path'], row['filename']).encode('utf-8')
            if os.path.exists(fname):
                return send_file(fname, as_attachment=True)
        abort(404)

    def playlist(self, fileid, fmt):
        sql = select([self.db_songtable], self.db_songtable.c.id == fileid)
        rows = self.dbc.execute(sql).fetchall()
        if fmt == 'm3u':
            return Response(render_template('playlist.m3u', rows=rows), mimetype='audio/x-mpegurl')
        if fmt == 'pls':
            return Response(render_template('playlist.pls', rows=rows, num=len(rows)), mimetype='audio/x-scpls')
        abort(404)

    def dir_playlist(self, args, fmt):
        try:
            path = args.get('p')
        except ValueError:
            return
        path = re.sub(r"/+", "/", path.rstrip('/'))
        rows = self.get_songs(args, path)
        if fmt == 'm3u':
            return Response(render_template('playlist.m3u', rows=rows), mimetype='audio/x-mpegurl')
        if fmt == 'pls':
            return Response(render_template('playlist.pls', rows=rows, num=len(rows)), mimetype='audio/x-scpls')
        abort(404)

    def folder_jpg(self, args):
        try:
            path = args.get('p')
        except ValueError:
            return
        path = re.sub(r"/+", "/", path.rstrip('/')).rstrip('#')
        pdir = os.path.realpath(re.sub (r"/+", "/", self.config['rootdir'] + '/' + path))
        # The result has to start with the configured rootdir
        if pdir[0:len(self.config['rootdir'])] != self.config['rootdir']:
            abort(404)

        fname = os.path.join(pdir, 'folder.jpg').encode('utf-8')
        if os.path.exists(fname):
            return send_file(fname)
        return send_file(os.path.join(os.path.dirname(__file__), 'static', 'no_image.jpg'))
        abort(404)

    # This method gets called if the requested AJAX function
    # does not exist as a method on this class
    def default_response(self, args):
        abort(404)
开发者ID:tinuzz,项目名称:traxx,代码行数:104,代码来源:traxxjax.py

示例10: AudioManager

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import idle [as 别名]
class AudioManager(object):
	"""
	Provides an interface to a running MPD instance.

	This class also accepts callbacks to be run after the following events are fired:
		'song change': Currently playing song has changed.
		               Callback should accept current song dict as its only argument.

	Callbacks can be registered as per the following example:

		music = SongData(config)

		@music.on('song change')
		def handle_song_change(song):
			print('Song is now {}.'.format(song['title']))

	Properties:
		current_song (dict): Information on the currently playing song.
		                     This dict includes the following keys:
							 artwork:    The URL for the song's artwork.
							 title:      The title of the current song.
							 artist:     The artist of the current song.
							 album:      The album of the current song.
							 length_sec: The length of the song in seconds.
							 time_sec:   The amount of time into the song, in seconds.
							 start_time: UNIX timestamp for when the song began playing.
							 length:     The length of the song as a time string.
							 time:       The amount of time into the song, as a time string.
							 progress:   The percentage of the amount of time into the song.
							 is_playing: True if the song is playing, False otherwise.
	"""

	def __init__(self, config):
		"""
		Creates a new interface to a running MPD instance.

		Arguments:
			config (dict): A dictionary of config values.
			               This is expected to include the following keys:
						   MPD_HOST:           The hostname of the MPD instance.
						   MPD_PORT:           The port that the MPD instance is running on.
						   MUSIC_DIR:          The directory that MPD looks for music in.
						   DEFAULT_ARTWORK:    The URL for default album artwork.
						   COVERS_DIR:         The directory to save album covers to.
						   COVERS_FILETYPE:    The file format to save album covers in.
						   AUDIO_EXTENSIONS:   List of allowed audio file extensions.
						   ARTWORK_EXTENSIONS: List of allowed artwork file extensions.
		"""
		self._locks = []
		self._callbacks = {}
		self._idling = False
		self._config = config
		self._mpd = MPDClient()
		self._musicgen = MusicGen()

		self._mpd.connect(config['MPD_HOST'], config['MPD_PORT'])

		self.current_song = None

		# Spin off a thread to wait for changes in MPD subsystems
		self._mpd_thread = Thread(target=self._mpd_idle, name='mpd-worker', args=())
		self._mpd_thread.setDaemon(True)
		self._mpd_thread.start()



	def on(self, name):
		"""
		Decorator for adding a callback method for events.

		Example:
			music = SongData(config)

			@music.on('song change')
			def handle_song_change(song):
				print('Song is now {}.'.format(song['title']))

		Arguments:
			name (str): The name of the event to register the callback for.
		"""
		def func_wrapper(func):
			self._callbacks[name] = func
			return func
		return func_wrapper

	def fire_event(self, name, *args, **kwargs):
		"""
		Fires the given event, passing the given arguments to the callback.

		Arguments:
			name (str): The name of the event to fire.
		"""
		func = self._callbacks.get(name, None)
		if not func is None:
			return func(*args, **kwargs)



	def _mpd_acquire(self):
		"""
#.........这里部分代码省略.........
开发者ID:nejsan,项目名称:sound_bubble,代码行数:103,代码来源:audio_manager.py


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