Pygame Mixer sound overlay

266 Views Asked by At

I'm trying to use mixer to play footsteps when the arrow keys are pressed. But whenever I do it obviously keeps detecting the button and continuously overlays the sound.

def walking():
    walk = pygame.mixer.Channel(2)
    walk_sound = mixer.Sound("Music/Walking.mp3")
    walk.play(walk_sound)
    if walk.get_busy():
        # Don't play anything

This is the function for the walking sound. Is there a way to not play anything if there is a sound playing?

if keypress[K_RIGHT]:
            self.rect.move_ip(x, 0)
            self.image = walk_right[walk_count // frame_count]
            display.blit(self.image, (self.rect.x, self.rect.y))
            walk_count += 1
            self.last = "right"
            walking()

This is part of my Player class and Move method to show where I call the walking sound function.

1

There are 1 best solutions below

0
Rabbid76 On

Create the channel and load the sound before the application loop at initialisation. Just start the sound in the walking function if the channel is not busy:

walk_channel = pygame.mixer.Channel(2)
walk_sound = mixer.Sound("Music/Walking.mp3")
def walking():
    if not walk_channel.get_busy():
        walk_channel.play(walk_sound)