Skip to content Skip to sidebar Skip to footer

Pygame.mixer.Sound.play Is Irregular Although Fired Regularly

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 so

Solution 1:

Here is an idea for an alternative approach. If the goal is to play a sound in regular intervals, you might get better results if you (dynamically) pad the sound to the desired interval length, and then simply loop it with Sound.play(loops=-1).

If there are just a handful of valid intervals, it might be easiest to store dedicated sound files and load the appropriate one.

Otherwise, the pygame.sndarray module provides access to a numpy array of the raw sound data, which makes it possible to dynamically generate sound objects of the desired length:

import pygame
import numpy


# Helper function
def getResizedSound(sound, seconds):

    frequency, bits, channels = pygame.mixer.get_init()

    # Determine silence value
    silence = 0 if bits < 0 else (2**bits / 2) - 1

    # Get raw sample array of original sound
    oldArray = pygame.sndarray.array(sound)

    # Create silent sample array with desired length
    newSampleCount = int(seconds * frequency)
    newShape = (newSampleCount,) + oldArray.shape[1:]
    newArray = numpy.full(newShape, silence, dtype=oldArray.dtype)

    # Copy original sound to the beginning of the
    # silent array, clipping the sound if it is longer
    newArray[:oldArray.shape[0]] = oldArray[:newArray.shape[0]]

    return pygame.mixer.Sound(newArray)


pygame.mixer.init()
pygame.init()

sound = pygame.mixer.Sound('sound.wav')

resizedSound = getResizedSound(sound, 0.2)
resizedSound.play(loops=-1)

while True:
    pass

Using just pygame (and numpy), this approach should have a good chance for an accurate playback.


Solution 2:

For me the thing worked much better, if i did:

pygame.mixer.pre_init(44100, -16, 2, 256)

before any of the pygame init functions.


Solution 3:

Ok, you should try using the other way to load a sound:

pygame.mixer.music.load(file=file_directory str)

To play the sound use:

pygame.mixer.music.play(loops=*optional* int, start=*optional* float)

Your code may look like this:

import pygame

pygame.init()
pygame.mixer.init()

sound = pygame.mixer.music.load('sound.wav')
def playSound():
    sound.pause()
    sound.play()

while True:
    pass

For me, that worked better but I am on python 3.7.2 . I don't know about python 3.5, but there aren't many difference between 3.5 and 3.7.2. That should work!


Post a Comment for "Pygame.mixer.Sound.play Is Irregular Although Fired Regularly"