我希望在递归函数中每隔几秒播放一次滴答声,并在中间休眠,具体取决于在GUI中设置bpm的高度。这将创造一个节拍。虽然由于Time.sleep()方法的延迟,节拍不是节奏。有时它很慢,然后加速并且不一致。
我可以使用替代方案在节拍之间给出一致的暂停吗?
这是我的代码:
class thalam():
def __init__(self,root,e):
self.lag=0.2
self.root=root
self.count=0
self.thread=threading.Thread(target=self.play)
self.thread.daemon=True
self.pause=False
self.e=e
self.tempo=60.0/120
self.count=0
def play(self):
winsound.PlaySound("tick.wav",winsound.SND_FILENAME)
time.sleep(self.tempo-self.lag)
self.count+=1
if self.count==990:
self.thread=threading.Thread(target=self.play)
self.thread.daemon=True
self.thread.start()
return
elif self.pause:
return
self.play()
def stop(self):
self.pause=True
def start(self):
self.pause=False
self.thread=threading.Thread(target=self.play)
self.thread.daemon=True
self.thread.start()
def settempo(self,a):
self.tempo=a
class Metronome(Frame):
def __init__(self,root):
Frame.__init__(self,root)
self.first=True
self.root=root
self.e=Entry(self)
self.e.grid(row=0,column=1)
self.e.insert(0,"120")
self.play=Button(self,text="Play",command=self.tick)
self.play.grid(row=1,column=1)
self.l=Button(self,text="<",command=lambda:self.inc("l"))
self.l.grid(row=0,column=0)
self.r=Button(self,text=">",command=lambda:self.inc("r"))
self.r.grid(row=0,column=2)
def tick(self):
if self.first:
self.beat=thalam(root,self.e)
self.beat.thread.start()
self.first=False
else:
self.beat.start()
self.play.configure(text="Stop",command=self.notick)
def notick(self):
self.play.configure(text="Start",command=self.tick)
self.beat.stop()
def inc(self,a):
if a=="l":
try:
new=str(int(self.e.get())-5)
self.e.delete(0, END)
self.e.insert(0,new)
self.beat.settempo(60.0/(int(self.e.get())))
except:
print "Invalid BPM"
return
elif a=="r":
try:
new=str(int(self.e.get())+5)
self.e.delete(0, END)
self.e.insert(0,new)
self.beat.settempo((60.0/(int(self.e.get()))))
except:
print "Invalid BPM"
return