Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 514
Manh Nguyen Huu Avatar asked Feb 22 '17 14:02

Manh Nguyen Huu


People also ask

How do you play two sounds at once in Python?

to play several (upto 8) sounds concurrently, you could use pygame. mixer. Sound() . pygame also provides a portable way to get keyboard input.

What is pygame mixer Sound?

mixer pygame module for loading and playing sounds is available and initialized before using it. The mixer module has a limited number of channels for playback of sounds. Usually programs tell pygame to start playing audio and it selects an available channel automatically.

How do you repeat a song on pygame?

music. play() to repeat the music indefinitely. Save this answer.


1 Answers

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

like image 90
The4thIceman Avatar answered Oct 22 '22 10:10

The4thIceman