我正在尝试在 Raspberry Pi 上制作一个非常简单的节拍器,以设定的时间间隔播放 .wav 文件,但计时明显不准确。 我真的不明白为什么,python的时间模块不准确吗?
我不认为处理播放音频的代码是瓶颈,因为如果我将其放入没有计时器的循环中,它会持续发出嘎嘎声。 使用下面的简单代码,声音将按节拍播放几次,然后随机关闭一个节拍,一遍又一遍。
import pygame
from time import sleep
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.mixer.init()
pygame.init()
BPM = 160
sound = pygame.mixer.Sound('sounds/hihat1.wav')
while True:
sound.play()
sleep(60/BPM)
我希望声音每 X 毫秒重复一次,精度至少为 +/-10 毫秒左右。这不现实吗?如果是这样,请提出替代方案。
最佳答案
问题原来是使用过大的 block 大小,这可能导致 pygame 播放声音较晚,因为较早的 block 已经排队。我的第一个建议是,我预计OP的代码会随着时间的推移而慢慢变化,这表明这样的事情会做得更好:
import pygame
from time import time, sleep
import gc
pygame.mixer.pre_init(44100, -16, 2, 256)
pygame.mixer.init()
pygame.init()
BPM = 160
DELTA = 60/BPM
sound = pygame.mixer.Sound('sounds/hihat1.wav')
goal = time()
while True:
print(time() - goal)
sound.play()
goal += DELTA
gc.collect()
sleep(goal - time())
即跟踪“当前时间”并根据经过的时间调整 sleep 时间。我在每次 sleep 之前明确执行“垃圾收集”(即 gc.collect()
),以使事情更具确定性。
关于Python:以设定的 BPM 间隔(<1 秒)播放音频的时间不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54236864/