我想制作一个基于 python 模块“mp3play”的小命令行音乐播放器。我想定期检查一首歌曲是否停止播放(并最终开始一首新歌曲),但用户应该能够在此期间输入新命令(如暂停音乐)。因此,我尝试为此使用 threading.Timer。但是,如果我在使用计时器调用的函数内,它会给我一个错误。正常调用函数时不会发生错误。这是我的(简化的)代码:
from threading import Timer
global currentmusic
def rep():
b = currentmusic.isplaying() #this is where the error occurs
if b:
print "Music is playing"
else:
print "Music has stopped"
t=Timer(5.0,rep) #repeat every 5 seconds
t.start()
currentmusic=playrandomfile() #loads a song and starts playing it
rep() #call the first time
当第二次调用 rep() 时,它在函数 isplaying() 中给我一个 MCI 错误,说它无法读取设备。我的问题:
我在 threading.Timer 的工作方式上犯了错误吗?(我该如何解决?)除了 threading.Timer 之外,还有其他方法可以实现我想要的东西吗?
到目前为止,我的想法是,currentmusic
从另一个线程访问可能是一个问题,但我不确定。我也不知道如何避免它。
谢谢帮助