- 1 year ago
Python - How can I play the same sound multiple times without them interrupting each other?
Comment
1 / 1
To play the same sound multiple times without them interrupting each other in Python, you can use the pygame
library. Here's an example:
pythonimport pygame
# Initialize pygame
pygame.init()
# Load the sound file
sound = pygame.mixer.Sound('path/to/sound.wav')
# Set the number of channels for simultaneous playback
pygame.mixer.set_num_channels(10)
# Play the sound multiple times
for _ in range(5):
channel = pygame.mixer.find_channel()
channel.play(sound)
# Wait for the sounds to finish playing
pygame.time.wait(int(sound.get_length() * 1000))
# Quit pygame
pygame.quit()
In this example, we're using the pygame.mixer.Sound
class to load the sound file, and pygame.mixer.set_num_channels
to set the number of channels for simultaneous playback. We then iterate over the desired number of repetitions and use pygame.mixer.find_channel
to get an available channel for playback. We play the sound on each channel using channel.play(sound)
.
Finally, we wait for the sounds to finish playing by using pygame.time.wait
and passing the duration of the sound in milliseconds.
Make sure you have the pygame
library installed before running the code. You can install it using pip install pygame
.