I am currently trying to repeat the sound every x ms - where x depends on the UDP packet I receive through the socket - and I decided to use pygame for this. I used this SO answer to repeat something every x ms: stack overflow
But now I have a problem that the sound plays very irregularly and makes a minimal working example where the problem persists:
import pygame
from pygame.locals import *
pygame.mixer.init()
sound = pygame.mixer.Sound('sound.wav')
def play_sound():
sound.stop()
sound.play()
pygame.init()
clock = pygame.time.Clock()
pygame.time.set_timer(USEREVENT+1, 200)
while True:
for event in pygame.event.get():
if event.type == USEREVENT+1:
play_sound()
Here is the waveform of what I recorded from the script through Audacity:

You see, for some reason, some samples reproduced longer than others. Not very good for some metronome that I want to build.
UPDATE:
pygame.time.set_timer, pygame.time.set_timer:
import pygame
from datetime import datetime
d = datetime.now()
pygame.mixer.init()
sound = pygame.mixer.Sound('horn_short.wav')
pygame.init()
while True:
if (datetime.now() - d).total_seconds() > 0.2:
sound.play()
d = datetime.now()
. Ubuntu 16.04, Python 3.5 64bit (Anaconda) pygame.