0

I am new to python and I am trying to create a simple metronome program. When I run my program I am running into a problem where the audio does not sound evenly spread out. I am running this on a Raspberry Pi 2 Model B. I have also tried using sleep() and time.monotonic(), but I ran into the same problem. Does anyone know what is going on here?

import time
import pygame

path = ("/home/pi/Documents/Loop/")
sound_file = ["kick.wav"]
pygame.mixer.init()
pygame.mixer.music.load(path + sound_file)

BPM = 60
BPMS = 60/(4*BPM)
#Metronome plays on quarter notes


delay = BPMS
past = 0
note = 1

while True:
    now = time.perf_counter()
    if now >= past + delay:
        if note == 1:
            pygame.mixer.music.play()
        elif note == 2:
            pygame.mixer.music.play()
        elif note == 3:
            pygame.mixer.music.play()
        elif note == 4:
            pygame.mixer.music.play()

        past = now
        note = note + 1
        if note > 4:
            note = 1
Leng1
  • 21
  • 4
  • Does this answer your question? [How can I do a precise metronome?](https://stackoverflow.com/questions/51389691/how-can-i-do-a-precise-metronome) – Andrew McClement Feb 26 '22 at 03:33
  • Not exactly, I've tried running the metronome both ways and I still run into the problem where the beats don't sound evenly spaced out. I thought it could have been the .wav file I was using so I changed it a few times and it made no difference. Could it be the Raspberry Pi itself? – Leng1 Feb 26 '22 at 19:44
  • I just tried running the program on my computer instead of my Raspberry Pi and again ran into the same problem. – Leng1 Feb 26 '22 at 20:40
  • I can't test it but system has to run many processes at the same time and it doesn't have to run python code with expected delays. Other problem can be that music runs in separated thread so it doesn't block rest of code - but Python has [GIL](https://realpython.com/python-gil/) which may block one thread when it has to run another thread. First you could display `now - past + delay` to see difference (like in answer in link in first comment) and maybe it will show how big is problem. – furas Feb 27 '22 at 03:05
  • @furas When I print ```now - past + delay``` there doesn't seem to be a problem with the values. I've been messing around with the program but have made no progress. – Leng1 Feb 27 '22 at 19:06
  • and we don't have your file to run it and test if this is problem on all computers. – furas Feb 27 '22 at 19:34

1 Answers1

0

When I initialize pygame with a buffer of 512 it seems to solve the problem: pygame.mixer.init(buffer=512)

Leng1
  • 21
  • 4