1️⃣

5.1 - Sounds

5.1 Sounds

This chapter will cover how to use sounds in pygame. Sounds can either be “background music” or results of an action (player actions/key presses/etc.).
Sounds are very similar to images. Load once, play many times. You have to load them first and then you can play them. Music will just play in the background when you call it too, and sounds will play at any time you call them to play.
The code below will play fire.wav whenever fireSound.play is called.
fireSound = pygame.mixer.Sound("fire.wav") # load the sound fireSound.play() # play the sound # we don't need to re-load the sound since you only need to load sounds once fireSound.play() # play the sound again!
Below, the -1 on the second line will keep looping. If you put, say, a 3 in there, then the music would play once and 3 more times. Basically, the parameter is how many times to loop the music, and -1 means infinitely loop the music.
pygame.mixer.music.load('jazz.wav') # load the music pygame.mixer.music.play(-1) # play the music pygame.mixer.music.stop() # stop the music
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.