I am playing around with building a python script that play rhythms like a drum machine. I have used PyGame to handle the audio. However I experience significant/unacceptable delays between calling play and hearing the actual audio.
I pasted the following code into the interactive interpreter, and then execute the last line again and again:
import pygame
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
s = pygame.mixer.Sound('snare.wav')
s.play(loops=0, maxtime=0, fade_ms=0)
The time between pressing enter and hearing the audio is by my best guess around 400ms, and indeed noticeable and unacceptable. The delay is approximately the same as if I click the play button in VLC and wait for the audio to play.
I have tried this on both Windows and Ubuntu with the same result. My computer is a bit old, an Intel Core i3, 2.53GHz, but I think this should not be a problem.
What can I do about this?
In a loop:
This code demonstrates the same lag.
for i in range(10):
print i
s.play(loops=0, maxtime=0, fade_ms=0)
sleep(2)
A possible solution is to decrease the buffer size (example 512):
I had the same problem a couple of minutes ago, and there's a solution that works for me in This other thread
It looks like an initialization problem, pygame doesn't get the buffers well if you init pygame first (or else XD). Initialize the mixer init() and pre_init() first, and experiment from there:
That should work :) Good luck!