0

我想用 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)
4

1 回答 1

1

这是另一个解决方案。

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()

值得注意的是,我已删除该wait_done呼叫。如果您像这样阻塞反应器线程,您可能会期望基于时间的事件调度不太可靠。

于 2018-05-09T00:36:41.933 回答