我想用Python制作一个节拍器。
我有2个声音文件。每秒应该播放第一个声音文件,每隔四秒钟播放第二个声音文件。
我找到了扭曲的模块,但无法弄清楚如何传递参数并迭代它。所以我有我想要迭代的变量计数器,但它不能使用以下代码:
import simpleaudio as sa
from twisted.internet import task
from twisted.internet import reactor
def beat(bpm, counter):
timeout = 60/bpm
l = task.LoopingCall(play_beat, counter=counter)
l.start(timeout)
reactor.run()
def play_beat(counter):
counter += 1
print(counter) #This prints always 2, I am expecting an iteration like 2, 3, 4, 5, 6 ...
if counter % 4 == 0:
wave_obj = sa.WaveObject.from_wave_file("wav/beat_end.wav")
else:
wave_obj = sa.WaveObject.from_wave_file("wav/beat_start.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
pass
beat(60, 1)
答案 0 :(得分:2)
这是另一种解决方案。
this.something = 'fruit'
值得注意的是,我已删除import simpleaudio as sa
from twisted.internet import task
from twisted.internet import reactor
def beat(bpm, wave_obj):
timeout = 60.0 / bpm
l = task.LoopingCall(play_beat, wave_obj)
l.start(timeout)
def play_beat(wave_obj):
wave_obj.play()
beat_start = sa.WaveObject.from_wave_file(...)
beat_end = sa.WaveObject.from_wave_file(...)
bpm = 60.0
bps = bpm / 60
reactor.callLater(0 / bps, beat, bpm / 4, beat_start)
reactor.callLater(1 / bps, beat, bpm / 4, beat_start)
reactor.callLater(2 / bps, beat, bpm / 4, beat_start)
reactor.callLater(3 / bps, beat, bpm / 4, beat_end)
reactor.run()
电话。如果你这样阻塞反应堆线程,你可能会对基于时间的事件安排不太可靠。