Music
Pygame supports several audio formats for music, such as MP3, WAV, Midi, OGG, and MOD.
To add audio using Pygame, you’ll need to load an audio file
pygame.mixer.music.load(‘path/to/audio/file.mp3’)
To play the audio use play()
pygame.mixer.music.play()
To control the playback, use the functions like pause(), unpause() and stop(). For example:
pygame.mixer.music.pause() # Pause the audio
pygame.mixer.music.unpause() # Unpause the audio
pygame.mixer.music.stop() # Stop the audio
You can also set the volume of the audio using the `set_volume()` function, which takes a value between 0.0 and 1.0:
pygame.mixer.music.set_volume(0.5) # Set vol to 50%
To ensure that the audio continues playing, you can add a loop:
while pygame.mixer.music.get_busy(): ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access