Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign sounds to channels in Pygame?

I'm trying to play multiple sounds simultaneously in Pygame. I have a background music and I want a rain sound to play continuously and play ocasional thunder sounds.

I have tried the following but my rain sound stops when thunder sound is playing. I have tried using channels but I don't know how to choose which channel to sound is playing from or if two channels can be played at once.

        var.rain_sound.play()

        if random.randint(0,80) == 10:                
            thunder = var.thunder_sound                
            thunder.play()

Thank you for your help

like image 563
Sorade Avatar asked Jun 25 '16 13:06

Sorade


1 Answers

Pygame's find_channel function makes it very easy to play audio on an unused channel:

sound1 = pygame.mixer.Sound("sound.wav")
pygame.mixer.find_channel().play(sound1)

Note that by default, find_channel will return None if there are no free channels available. By passing it True, you can instead return the channel that's been playing audio the longest:

sound1 = pygame.mixer.Sound("sound.wav")
pygame.mixer.find_channel(True).play(sound1)

You may also be interested in the set_num_channels function, which lets you set the maximum number of audio channels:

pygame.mixer.set_num_channels(20)
like image 153
Pikamander2 Avatar answered Sep 20 '22 07:09

Pikamander2