pygame.mixer.Sound.play is irregular although fired regularly

Issue #322 new
Dennis Scheiba
created an issue

I currently try to repeat a sound every x ms - where x is dependent on an UDP packet I receive via socket - and I decided to use pygame for that. I used this SO answer to repeat something every x ms: http://stackoverflow.com/a/18954902/3475778

But now I have the problem, that the sound is played very irregular and made 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:
    # clock.tick(30)
    for event in pygame.event.get():
        if event.type == USEREVENT+1:
            play_sound()

Here is the waveform of what I have recorded from the script via Audacity:

enter image description here

You see that for some reason some samples were played longer than the others. Not very nice for some kind of metronome I want to build.

System is Python 3.5 64bit under Windows 10 Home.

Comments (5)

  1. Dennis Scheiba reporter

    It seems it is a problem of pygame.mixer.Sound, because this code w/o set_timer has the same problem

    import pygame
    from datetime import datetime
    
    d = datetime.now()
    
    pygame.mixer.init()
    sound = pygame.mixer.Sound('sound.wav')
    
    pygame.init()
    clock = pygame.time.Clock()
    
    while True:
        clock.tick(30)
        if (datetime.now() - d).total_seconds() > 0.2:
            sound.play()
            d = datetime.now()
    
  2. Log in to comment