I\'ve made a button class that checks if a button is selected (when the mouse is hovering over the button). When the button is selected, unselected or clicked it plays a wav
Decreasing the size of the buffer will reduce the latency. The buffer must be a power of 2. The default buffer is 4096, but you can change it when you initialize mixer as shown below:
pygame.mixer.init(44100, -16, 2, 64)
More information can be found on the pygame docs
I also had problems with sound lagging. I found that calling pygame.mixer.pre_init()
before pygame.init()
solved my problems:
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.init()
I had a sound delay, too. Now, this works fine for me:
pg.mixer.pre_init(44100, -16, 1, 512)
pg.init()
pg.mixer.init()
With pg.mixer.pre_init(22100, -16, 2, 64)
the sound plays faster but is twisted, okay for sound effects but not for real music as background.
Simply decreasing the size of the buffer, as often suggested for this problem, did not work for me. I found this solution. When initiating the mixer twice, the delay completely disappeared:
import pygame
pygame.mixer.pre_init(22050, -16, 2, 1024)
pygame.init()
pygame.mixer.quit()
pygame.mixer.init(22050, -16, 2, 1024)
It's a bit dirty and I don't know why it works, but hopefully it solves the problem for some people.
Tested on Ubuntu 16.04 LTS with Python 3.6 and pygame 1.9.4
In my situation the delay was between 0.2 and 0.5 sec. To call pygame.mixer.pre_init() is a very good solution but the delay also depends on the given values.
Found an answer posted in another question, which suggest changing the buffer size.