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


Python MPDClient.connect方法代码示例

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


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

示例1: run

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def run():
	if not request.form['url']:
		flash('Please provide an URL')
		return redirect(url_for('welcome'))
	# do stuff
	try:
		p = subprocess.check_output(['/usr/bin/python', 'youtube-dl', '-t', '--no-progress', '--extract-audio', '--max-quality=18', '--audio-format=mp3', '--', request.form['url']])
	except:
		flash("Nice try.")
		return redirect(url_for('welcome'))
	m = re.search("\[ffmpeg\] Destination: (.+?)\s", p)
	myfile = m.group(1)
	shutil.move(myfile, "static/%s" % myfile)
	try:
		mpd = MPDClient()
		try:
			mpd.connect(host="trillian", port="6600")
			mpd.add("http://toolbox.labor.koeln.ccc.de/static/%s" % myfile)
		except:
			raise
	except:
		flash('mpd failure')
		return redirect(url_for('welcome'))
	flash('your song has been added to the playlist')
	return redirect(url_for('welcome'))
开发者ID:MechanisM,项目名称:youconv,代码行数:27,代码来源:youconv.py

示例2: connect

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def connect(host):
    '''
    Connect to mpd.
    '''
    logger.info("Connecting to mpd on " + host)
    # Parse the host address
    url = urlparse('//' + host)

    hostname = url.hostname
    port = url.port

    # Default to localhost port 6600
    if hostname == None:
        hostname = 'localhost'
    if port == None:
        port = 6600

    logger.debug('Hostname: ' + hostname)
    logger.debug('Port: ' + str(port))

    try:
        mpdc = MPDClient()
        mpdc.connect(hostname, port)
        logger.debug('Connection succeeded')
        logger.debug('MPD status: ' + str(mpdc.status()))
    except OSError as exception:
        logger.info('Can not connect to mpdd on ' + host)
        logger.debug('Exception: ' + str(exception.errno))
        logger.debug('Message: ' + exception.strerror)
        sys.exit(1)

    return(mpdc)
开发者ID:deadbok,项目名称:RadioPi,代码行数:34,代码来源:mpd.py

示例3: fav_song

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def fav_song(request):
    c = MPDClient()
    c.connect("localhost", 6600)
    form = FavSongForm(request.POST or None)
    if not form.is_valid():
        for error in form.errors:
            messages.add_message(
                request,
                messages.ERROR,
                "Error: {0}".format(form.errors[error][0])
            )
    else:
        filename = form.cleaned_data['filename']
        track = get_track(filename, in_playlist=False)
        if not track:
            messages.add_message(
                request,
                messages.ERROR,
                "Error: Cannot find song."
            )
        else:
            messages.add_message(
                request,
                messages.INFO,
                "Faved: {artist} - {title}".format(
                    artist=track['artist'], title=track['title'])
            )
            song_obj = get_song(filename, track['artist'], track['title'])
            SongFav(song=song_obj).save()
    return redirect(request.GET.get("from", "/"))
开发者ID:allo-,项目名称:mpdsongvote,代码行数:32,代码来源:views.py

示例4: onevent

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def onevent(msg):
    # add song if needed
    client = MPDClient()
    client.connect("localhost", 6600)
    client.use_unicode = True
    if client.status()["playlistlength"] == '0' and autoaddstate == 1:
        song = choose_from_list(current_list)
        client.add(song)
        # while client.status()['state']=='stop':
        client.play()

    # currentsong info
    if 'player' in msg or 'playlist' in msg:
        print("publish currentsong")
        currentsong = client.currentsong()
        print(currentsong)
        # pre-treat the data if artist/title not present:
        if 'title' not in currentsong.keys():
            currentsong['artist'] = "?"
            if 'file' in currentsong.keys():
                currentsong['title'] = currentsong['file'].split('/')[-1]
        yield app.session.publish('radio.updatesong', currentsong)

        # player status info
    if ('player' in msg or
            'mixer' in msg or
            'options' in msg or
            'playlist' in msg):
        print("publish player status")
        status = client.status()
        status[u'autoadd'] = autoaddstate
        yield app.session.publish('radio.updatestatus', status)

    # playlist info
    if 'playlist' in msg:
        print("publish playlist")
        playlist = client.playlistinfo()
        print(playlist)
        playlist_trim = []
        for song in playlist:
            song_trim = {}
            if 'http' in song['file']:
                song_trim['artist'] = song['file']
                song_trim['title'] = ''
                song_trim['time'] = 9999
                song_trim['id'] = song['id']
            else:
                if 'title' not in song.keys() or 'artist' not in song.keys():
                    song_trim['artist'] = "?"
                    if 'file' in song.keys():
                        song_trim['title'] = song['file'].split('/')[-1]
                else:
                    song_trim['artist'] = song['artist']
                    song_trim['title'] = song['title']
                song_trim['id'] = song['id']
                song_trim['time'] = song['time']
            playlist_trim.append(song_trim)
        yield app.session.publish('radio.updateplaylist', playlist_trim)

    client.close()
开发者ID:crazyiop,项目名称:hipsterRadio,代码行数:62,代码来源:autoadd_update.py

示例5: main

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def main():
    parser = argparse.ArgumentParser(description='wake up with music')
    parser.add_argument('--playlist',
        type=str, help='foo help', default="Alarm Clock")
    parser.add_argument('--sleep',
        type=str, help='foo help', default="90 min")
    args = parser.parse_args()


    r = rxv.RXV("192.168.1.116")
    r.on = True
    time.sleep(0.5)
    r.sleep = args.sleep
    r.input = "HDMI4"
    r.volume = START_VOLUME

    cli = MPDClient()
    cli.connect("dom.wuub.net", 6600)
    cli.clear()
    cli.load(args.playlist)
    cli.play()

    for vol in range(START_VOLUME, MID_VOLUME, 1):
        r.volume = vol
        time.sleep(0.5)

    time.sleep(30)
    requests.get("http://dom.wuub.net/api/lights/small/on")

    for vol in range(MID_VOLUME, TARGET_VOLUME, 1):
        r.volume = vol
        time.sleep(2)

    time.sleep(60)
    requests.get("http://dom.wuub.net/api/lights/large/on")
开发者ID:omy09,项目名称:homeautomation,代码行数:37,代码来源:alarm_clock.py

示例6: __init__

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

        try:
            self.client.connect(HOST, PORT)
        except SocketError:
            print("Failed to connect to MPD, exiting")
            sys.exit(1)
        self.notify = SongNotify()

        self.song = None
        self.updateSong(self.client.currentsong())

    def watch(self):
        while True:
            self.client.send_idle()
            select([self.client], [], [])
            changed = self.client.fetch_idle()
            if "player" in changed:
                self.updateSong(self.client.currentsong())

    def updateSong(self, song):
        if not "id" in song:
            return

        if self.song and song["id"] == self.song.id:
            return

        self.song = Song(song)

        if self.client.status()["state"] == "play":
            self.notify.newSong(self.song)
        else:
            print(self.client.status()["state"])
开发者ID:vi-n,项目名称:MpdPopUp,代码行数:37,代码来源:popup.py

示例7: yoinkMPD

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def yoinkMPD(cod):
    mpd = MPDClient(use_unicode=True)
    mpd.timeout = None
    mpd.idletimeout = None
    mpd.connect(cod.config["mpd"]["host"], cod.config["mpd"]["port"])

    return mpd
开发者ID:Xe,项目名称:code,代码行数:9,代码来源:mpdclient.py

示例8: __enter__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
 def __enter__(self):
     client = MPDClient(use_unicode=True)
     self.client = client
     client.timeout = 1
     client.idletimeout = None
     client.connect("131.urlab.be", 6600)
     return client
开发者ID:UrLab,项目名称:api,代码行数:9,代码来源:views.py

示例9: play_playlist

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def play_playlist(name):
    client=MPDClient()
    mopidyAddress = 'localhost'
    mopidyPort = 6600

    client.timeout = 10
    client.idletimeout = None
    client.connect(mopidyAddress,mopidyPort)
    #client.password('IlPits2013')
    client.clear()
    if playlist_exists(name):
        client.load(name)
    spotify_lists = get_spotify_playlists()
    name = name.encode('utf-8')
    print name
    #print spotify_lists
    if name in spotify_lists:
        add_spotify_directory(name)
    #time.sleep(1)
    if name == 'Pierre':
        client.shuffle()

    #client.setvol(50)
    #client.play()
    client.disconnect()
    return
开发者ID:NilsNoreyson,项目名称:phoneBookServer,代码行数:28,代码来源:get_phonebook_files.py

示例10: print_files

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def print_files():
    sync_files = open('/media/satellite_mpds/files2sync.txt','a')
    client=MPDClient()
    mopidyAddress = 'localhost'
    mopidyPort = 6600

    client.timeout = 10
    client.idletimeout = None
    client.connect(mopidyAddress,mopidyPort)
    #client.password('IlPits2013')
    files = client.playlistinfo()
#    files = client.lsinfo(foldername)
    files = [x['file'] for x in files]
    files = sorted(files)
    outfiles=[]
    for f in files:
        real_path=os.path.join(music_dir,f)
        if os.path.exists(real_path):
            if os.path.islink(real_path):
                target_path = os.readlink(real_path)
                abs_target_path = os.path.realpath(real_path)
                target_path_rel_to_music_dir = os.path.relpath(abs_target_path, music_dir)
                print target_path_rel_to_music_dir
                sync_files.write(target_path_rel_to_music_dir+'\n')
                outfiles.append(target_path_rel_to_music_dir)
            sync_files.write(f+'\n')
            outfiles.append(f)
            print('ADDED')
            print f
    sync_files.close()
    #print(files)
    client.disconnect()
开发者ID:NilsNoreyson,项目名称:phoneBookServer,代码行数:34,代码来源:get_phonebook_files.py

示例11: connect

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
	def connect(self,port):
		global client
		connection = False
		retry = 2
		while retry > 0:
			client = MPDClient()	# Create the MPD client
			try:
				client.timeout = 10
				client.idletimeout = None
				client.connect("localhost", port)
				log.message("Connected to MPD port " + str(port), log.INFO)
				connection = True
				retry = 0
			except:
				log.message("Failed to connect to MPD on port " + str(port), log.ERROR)
				time.sleep(0.5)	# Wait for interrupt in the case of a shutdown
				log.message("Restarting MPD",log.DEBUG)
				if retry < 2:
					self.execCommand("service mpd restart") 
				else:
					self.execCommand("service mpd start") 
				time.sleep(2)	# Give MPD time to restart
				retry -= 1

		return connection
开发者ID:MicroSDHC,项目名称:piradio,代码行数:27,代码来源:radio_class.py

示例12: delegateInput

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
    def delegateInput(self, texts):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        for text in texts:
            if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
                self._logger.debug("Preparing to start music module")
                # check if mpd client is running
                try:
                    client = MPDClient()
                    client.timeout = None
                    client.idletimeout = None
                    client.connect("localhost", 6600)
                except:
                    self._logger.critical("Can't connect to mpd client, cannot start music mode.", exc_info=True)
                    self.mic.say(
                        "I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify.")
                    return

                self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
                self._logger.debug("Starting music mode")
                music_mode = MusicMode(self.persona, self.mic)
                music_mode.handleForever()
                self._logger.debug("Exiting music mode")
                return

        self.brain.query(texts)
开发者ID:gregnorth,项目名称:jasper-client,代码行数:29,代码来源:conversation.py

示例13: __init__

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

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

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

示例14: test

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
def test():
    """
    ## TODO:     Test qui ne fonctionne que sur mon ancienne instalation
        A refaire
    """
    #pod='http://podcast.college-de-france.fr/xml/histoire.xml'
    pod="http://radiofrance-podcast.net/podcast09/rss_11074.xml"
    w=MPDPodcast(podcast_path="/media/Disque_2/mp3/laurent/Podcast")
    w.add_flux(pod)
    w.print_flux()
    w.remove_item(1)
    #w.remove_flux(1)
    #w.print_items(1)
    path=w.download_item(3)

    #Made the item readed
    path=path.split("/")[-2:]
    path=os.path.join(path[0], path[1])
    client=MPDClient()
    client.connect('localhost', 6600)
    song,=client.search('file', path)
    client.sticker_set('song', song['file'], 'last_up',int(song['time']))
    w.check_item()
    w.purge_readed()
    #    w.remove_dowloaded_item(3)
    w.remove_item(4)

    w.update()
开发者ID:RaoulChartreuse,项目名称:mpd_bookmark,代码行数:30,代码来源:mpd_podcast.py

示例15: IndiMPDClient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import connect [as 别名]
class IndiMPDClient(object):
	def __init__(self):
		self.config = IndiMPCConfiguration()
	
		self.setup_dbus()
		self.setup_client()
		self.oldstatus = ""
		self.oldsongdata = ""

		pynotify.init("indimpc")
		self.notification = pynotify.Notification("indiMPC started")
		self.notification.set_hint("action-icons", True)
		gobject.timeout_add(500, self.status_loop)

		if self.config.general_grab_keys:
			self.grab_mmkeys()

	def setup_dbus(self):
		dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
		self.bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
	
	def setup_client(self):
		global MPD
		try:
			self.mpdclient = MPDClient()
			self.mpdclient.connect(self.config.mpd_host, self.config.mpd_port)
			if self.config.mpd_password not in ("", None):
				self.mpdclient.password(self.config.mpd_password)
			self.oldstatus = self.mpdclient.status()["state"]
		except socket.error, e:
			sys.stderr.write("[FATAL] indimpc: can't connect to mpd. please check if it's running corectly")
			sys.exit()
开发者ID:ThomasAdam,项目名称:indimpc,代码行数:34,代码来源:indimpc.py


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