I am trying to make a very simple metronome on a Raspberry Pi that plays a .wav file at a set interval, but the timing is audibly inaccurate. I really can't figure out why, is python's time module that inaccurate?
I don't think the code that handles playing the audio is the bottleneck since if I put it in a loop with no timer it will rattle consistently. With the simple code below, the sound will play on beat a few times and then one beat will be off randomly, over and over.
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)
I expect to get the sound to repeat every X milliseconds with an accuracy of at least +/-10ms or so. Is that unrealistic? If so please suggest an alternative.