我只是想弄清楚如何使用Spotipy继续检查是否在Spotify上播放一首歌曲,然后将其打印,并且当歌曲更改时,还应该打印出更改的内容。这应该一直持续到程序关闭。到目前为止,这就是我所拥有的。
import spotipy
import spotipy.util as util
class SongAsAppName:
def __init__(self):
self.new_song = ''
scope = 'user-read-currently-playing'
self.token = util.prompt_for_user_token(username, scope,
CLIENT_ID, CLIENT_SECRET,
redirect_uri='http://localhost:8888/callback')
self.spotify = spotipy.Spotify(auth=self.token)
self.current_track = self.spotify.current_user_playing_track()
def set_song_info(self, new_song):
if self.song != new_song:
self.get_song_info()
self.current_track = new_song
self.print_song_info()
def get_song_info(self):
song_title = self.current_track['item']['name']
artist_name = self.current_track['item']['artists']
for entry in artist_name:
artist_name = entry['name']
full_title = (song_title + ' - ' + artist_name)
return full_title
def print_song_info(self):
self.song = self.get_song_info()
while True:
if self.new_song != self.song:
print('Playing song: ' + self.song)
self.new_song = self.song
test = SongAsAppName()
test.print_song_info()
我认为这与用歌曲覆盖new_song有关,并且卡在那里。例如,它打印出:
Playing song: Natural Disasters - Enon
当下一首歌曲播放时,不会打印出该歌曲的名称。整天工作并完成这个小项目之后,大脑才被炸掉,因此不胜感激!
--------------------------------------------------------------------------
在这里尝试不同的东西,但总体思路相同。下一首歌曲播放时,歌曲似乎没有更新。
import spotipy
import spotipy.util as util
import sched
import time
new_song = ''
s = sched.scheduler(time.time, time.sleep)
scope = 'user-read-currently-playing'
token = util.prompt_for_user_token(username, scope,
CLIENT_ID, CLIENT_SECRET,
redirect_uri='http://localhost:8888/callback')
spotify = spotipy.Spotify(auth=token)
current_track = spotify.current_user_playing_track()
def get_song_info():
while True:
song_title = current_track['item']['name']
artist_name = current_track['item']['artists']
for entry in artist_name:
artist_name = entry['name']
full_title = (song_title + ' - ' + artist_name)
s.enter(10, 1, get_song_info)
return full_title
def print_song_info(new_song):
while True:
new_song = new_song
song = get_song_info()
if new_song != song:
print('Playing song: ' + song)
print(new_song)
new_song = song
print(new_song)
SongAsAppName.s.enter(10, 1, print_song_info, (new_song,))
s.enter(10, 1, print_song_info(new_song))
print_song_info()
答案 0 :(得分:2)
您通过编辑发布的代码存在一些问题。我认为您正在尝试在new_song
的全局范围内使用print_song_info
,但这不是它们的工作方式。您已重新定义print_song_info
以接受参数,以使最后一行无法运行。我不确定为什么在while True
中有get_song_info
,因为它总是在第一次迭代后返回。永远不会到达print_song_info
中的最后一行。
我以sched
为例删除了代码。这使用time()
来生成一个每秒仅更改一次的字符串,但是我认为它的行为与您预期的类似,而没有使用线程或异步。
import sched
import time
s = sched.scheduler(time.time, time.sleep)
current_song = ''
def get_song_info():
global current_song
seconds = int(time.time())
current_song = "This string changes once per second " + str(seconds)
s.enter(0.5, 1, get_song_info)
def print_song_info(song):
if current_song != song:
print(current_song)
s.enter(0.1, 1, print_song_info, (current_song,))
get_song_info()
print_song_info('')
s.run()