Manh Nguyen Huu
Manh Nguyen Huu

Reputation: 381

How can I play multiple sounds at the same time in pygame?

I have the music that is always run in the background and some activities that would play sound when triggered. The music works fine.

pygame.mixer.music.load(os.path.join(SOUND_FOLDER, 'WateryGrave.ogg'))

The problem I have is that when there are 2 or more activities triggering sounds, then only one would be played (not including the background music) and the rest are muted. Is there any solution to this?

Upvotes: 16

Views: 24388

Answers (1)

The4thIceman
The4thIceman

Reputation: 3889

you can add sounds to different channels using the mixer:

pygame.mixer.Channel(0).play(pygame.mixer.Sound('sound\gun_fire.wav'))
pygame.mixer.Channel(1).play(pygame.mixer.Sound('sound\enemy_hit.wav'))

Within each channel you can still only play one sound at a time, but you can group sounds into different channels if they would need to play at the same time.

You can add more channels like this:

pygame.mixer.set_num_channels(10)  # default is 8

A simple example. For the docs on Channels, go to:

https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Channel

Upvotes: 28

Related Questions