如何设置Timer来控制循环内的函数调用?

时间:2016-05-02 20:37:13

标签: python list timer echonest

我有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获取所有可播放的idforeign_id),并将其传递给play(id_)

并将每首歌duration传递给time.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
然而,只有一首歌在播放,而递归就会消失。

如何更正代码,以便我可以使用按顺序播放所有曲目,只运行一次代码

1 个答案:

答案 0 :(得分: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