Playing a sound
Like images, this will assume all your sound files are in your project folder. You can only have one track of “background” music playing at a time. You can, however, have multiple sound effects at once.
Playing a background song is dead easy… one command to load it, one command to play. Don’t put this in your loop! It should go where colours are declared etc.
pygame.mixer.music.load('background.mp3') pygame.mixer.music.play(-1) # 0 = play once, -1 = loop
It really is important that your pygame.mixer.music.load is not in your game loop. Every time you run it you are reloading the file into memory, slowing your sstem down!
Make sure you only load the sound effect once. You can use it multiple times, but it will chew up your system memory very quickly if you put the load inside your game loop!
To find good sound effects online, I like freesound.org
Create a sound effect variable…
BOUNCE_SOUND = pygame.mixer.Sound('sound-effect.wav'))
Then in your main game loop, when you want the sound to play…
Note: Sound effects have to be WAV files.