gpt4 book ai didi

python - 如何设置计时器来控制循环内的函数调用?

转载 作者:太空宇宙 更新时间:2023-11-03 16:38:55 24 4
gpt4 key购买 nike

我有这个函数,可以播放Spotify:

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

接下来的循环会遍历所有播放列表歌曲,获取所有可播放的id(foreign_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

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

如何更正代码,以便让函数按顺序播放所有轨道,仅运行代码一次

最佳答案

看起来 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

关于python - 如何设置计时器来控制循环内的函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36991241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com