Skills of Adding Sound in python pygame Game
- 2021-12-11 07:56:28
- OfStack
Pygame
Adj.
mixer
The module can play one or more sounds according to the command, and can also mix these sounds in one.
There are four steps to get sound:
1. Start the mixer process
First, in the setup section of your code, start
mixer
Process.
pygame.init()
pygame.font.init()
pygame.mixer.init() # add this line
2. Create a sound directory
First, create a new directory in your game directory, which can be named
sound
s = 'sound'
3. Add sound to Pygame
Find the sound file and move it to your game directory
sound
Folder.
Suppose you have downloaded a file called
ouch.ogg
In the settings section of your code, create a variable that represents the sound file you want to use:
ouch = pygame.mixer.Sound(os.path.join(s, 'ouch.ogg'))
Step 4 Trigger a sound
To use a sound, all you have to do is call this variable when you want to trigger it.
for enemy in enemy_hit_list:
pygame.mixer.Sound.play(ouch)
score -= 1
Add: Add background music
If you have music or exciting sound effects that you want to play in the background of your game, you can use
Pygame
In
mixer
In the module
music
Function.
In your settings section, load the music file:
music = pygame.mixer.music.load(os.path.join(s, 'music.ogg'))
Then, start the music:
pygame.mixer.music.play(-1)
A value of-1 tells Pygame to loop the music file indefinitely. You can set it to any number from 0 to higher to define how many times the music loops before it stops.