Python中精确的循环计时

2024-10-01 17:22:14 发布

您现在位置:Python中文网/ 问答频道 /正文

对于this project我正在设计一个音序器/鼓式机器,它应该能够以精确的速度发送MIDI音符。示例:每2秒16个音符(即在音乐术语中,BPM 120时每小节16个1/16个音符),即每125毫秒一个音符。在

我在想:

import time

def midi_note_send(...):
    ....

while True:
    midi_note_send(...)
    time.sleep(0.125)

如果我这样做,怎么确定它是125毫秒? 这个循环的1000次迭代是否有使用126秒而不是125秒的风险?如果是这样,如何有一个更精确的循环?在

最后一点:一个好的鼓槌机应该能够在1小时内保持120 BPM的节奏,精度误差为<;1秒。
使用的平台:Linux+RaspberryPi,但这个问题通常是有效的。在


Tags: project机器send示例time音乐this速度
3条回答

至少,您应该考虑midi_note_send的计算时间

import time

# Define a generator for timing
def next_time(t0, dt):
    while 1:
        t0 += dt
        yield t0

# Initialize timer and start loop
timer = next_time(time.time(), 0.125)
while True:
    midi_note_send(...)
    time.sleep(next(timer) - time.time())

你可以用绝对时间(fromtime.time())来计算你的睡眠时间。在

starttime = time.time()
for i in range(100):
    midi_note_send(...)
    sleep_duration = (i + 1) * 0.125 - time.time() + starttime
    time.sleep(sleep_duration)

正如我展示的here

import time
def drummer():
    counter = 0
    # time.sleep(time.time() * 8 % 1 / 8) # enable to sync clock for demo
    while counter < 60 * 8:
        counter += 1
        print time.time()
        time.sleep(.125 - time.time() * 8 % 1 / 8)

这个定时器调整每一个拍子并重新排列。在

调整几乎不需要时间:

^{pr2}$

也就是说每次都需要0.25微秒

为了准确起见:

1488490895.000160
1488490895.125177
1488490895.250167
1488490895.375151
1488490895.500166
1488490895.625179
1488490895.750178
1488490895.875153

大约28微秒的音程。在本地运行更长的时间会产生大约130μs的总漂移(+-65μs),但是,由于它每拍都与时钟同步,因此不会随时间而偏离。在

相关问题 更多 >

    热门问题