1

我有这个function,它播放Spotify

#a function to play Spotify
def play(id_):
    print 'playing', id_
    os.system("osascript -e 'tell application \"Spotify\" to play track \"%s\"'" % (id_,))

以及以下loop遍历所有playlist歌曲的 , 获得所有可播放id的 ( foreign_id) , 将它们传递给play(id_),

并传递每首歌曲durationtime.sleep()停止循环,直到每首歌曲完成,再次重复循环:

for i, song in enumerate(song_playlist):
            #we need to track each song id
            song_id = song_playlist[i]['id']
            #in order to get song 'duration', access 'song/profile response' and pass the id as an argument
            response_profile = en.get('song/profile', id=song_id, bucket="audio_summary")
            song_profile = response_profile['songs']
            dur = song_profile[0]['audio_summary']['duration']
            #convert to miliseconds     
            dur *= 1000
            print int(round(dur))                           
            #now we access each song 'foreign_id' 
            for track in song:
                track = song['tracks'][i]
                track_id = track['foreign_id'].replace('-WW', '')           
            print '{0} {2} {1}'.format(i, song['artist_name'], song['title'])
            #call the function for each track
            play(track_id) #CALL FUNCTION HERE
            time.sleep(int(round(dur))) # SET INTERVAL CALL TO EACH SONG DURATION

但是,只有一首歌曲播放,递归消失了。

如何更正代码,以便让函数按顺序播放所有曲目,只运行一次代码

4

1 回答 1

1

看起来play(track_id)应该在for track in song循环内。您需要将其缩进 1 级。

for i, song in enumerate(song_playlist):
    # Code as before ...
    for track in song:
        track = song['tracks'][i]
        track_id = track['foreign_id'].replace('-WW', '')           
        print '{0} {2} {1}'.format(i, song['artist_name'], song['title'])
        play(track_id) #CALL FUNCTION HERE
    time.sleep(int(round(dur))) # SET INTERVAL CALL TO EACH SONG DURATION
于 2016-05-02T20:44:38.040 回答