IN THIS ADVENTURE, you’ll learn how to use sounds and music with Python and PyGame
. PyGame
makes sounds and music available, including a whole load of useful functions that make it straightforward to add them to your program.
You’ll make a loop that plays sounds, sounds that play when you press the keys on the keyboard and a basic music player. On top of this, you’ll improve the sprite walking program that you made in Adventure 8 by adding music and sounds to it.
Before you start, you’ll need to download the sample sounds and music needed for this adventure. You can find out how to do this in the Appendix. Make sure you save the files in the Adventure 9
folder.
Let’s get going.
In this first program, you’ll learn how to play sounds. The program you make here will form the basis of other programs that you create in the adventure. Sounds are very important in games. They’re an excellent way of sharing information with users and setting tone, all with just some noises. For example, in many video games you can often hear certain enemies sneaking up on you or you can tell if you managed to hit an object with your sword based on the sound it makes.
The program is very straightforward (see Figure 9-1); all it does is play a single sound before closing.
play.py
in the Adventure 9
folder.PyGame
:
import pygame
pygame.init()
hit.wav
, which is the name of the sound file. Add it to your program now:
sound = pygame.mixer.Sound('hit.wav')
sound.play()
pygame.time.wait(int(sound.get_length()) * 1000)
PyGame
window will open—this isn’t needed for the sound to play.In PyGame
, you can load several sounds at once. In this program (see Figure 9-2), you’ll create a loop that plays sounds. Every fourth time the loop repeats it will play a different sound. By adapting the program, you can make music or drum loops.
noiseLoop.py
in the Adventure 9
folder.PyGame
:
import pygame
pygame.init()
clock = pygame.time.Clock()
crash.wav
and hit.wav
. The program now needs to load these sounds:
crash = pygame.mixer.Sound('crash.wav')
hit = pygame.mixer.Sound('hit.wav')
count = 0
while count < 200:
if count % 4 == 0:
crash.play()
else:
hit.play()
count += 1
clock.tick(2)
In this program, you’ll use the keyboard to control sounds (see Figure 9-3). When you press the a or s key, it will play a sound. You can add your own sounds and keys by extending the program.
Adding sounds when keys are pressed is used in many video games. For example, in fantasy adventure games characters make a noise when they swing their sword, fire their bow or cast a spell.
keyboardSounds.py
in the Adventure 9
folder.PyGame
in the program:
import pygame
pygame.init()
windowSize = [400, 300]
pygame.display.set_mode(windowSize)
hit = pygame.mixer.Sound("hit.wav")
crash = pygame.mixer.Sound("crash.wav")
done = False
while not done:
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
hit.play()
if keys[pygame.K_s]:
crash.play()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.quit()
You’re now going to learn how to use music with PyGame
and Python. PyGame
’s music features work slightly differently than its sound features, and some of the functions vary slightly from the sound functions. Also, only one music file can be loaded at a time, unlike sounds, which can have several loaded at once.
Games use music really well to help set the mood and feel of the game. For example, in mystery games, tense and dramatic music is used to build suspense. Fantasy games often use music that features older, folk instruments and avoid modern music. You’ll create a program that plays a single music file, a file that adds a wobbling volume effect to the sound and a GUI that can control the volume of the music and pause it.
This first program will get you used to using music with PyGame
and Python (see Figure 9-4). It will play a single music file. Like the sound programs you created earlier, it won’t open a window when the program runs.
music.py
in the Adventure 9
folder.PyGame
:
import pygame
pygame.init()
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.wait(200)
Next, you’re going to add tremolo to some music (see Figure 9-5).
Tremolo has many uses in music. If the speed of the effect is really fast, it sounds choppy. Effects like this have some use in computer games. Tremolos can be used to make things sound spooky or exciting, depending on the speed.
tremolo.py
in the Adventure 9
folder.PyGame
and the math
module. The math
module is used later in the program to add the tremolo wobble to the music:
import math
import pygame
pygame.init()
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play()
count = 0
while pygame.mixer.music.get_busy():
sin()
function creates the wave used to set the volume and the abs()
function makes sure the value is positive:
volume = abs(math.sin(count))
pygame.mixer.music.set_volume(volume)
count += 0.2
pygame.time.delay(200)
Now for something really exciting. In this next program you’ll use Tkinter
and PyGame
together to make a music player (see Figure 9-6). Your program will create a GUI that allows you to play and pause a song using a button and control its volume with a slider.
musicPlayer.py
in the Adventure 9
folder.PyGame
and Tkinter
. This code is no different to the code you’d use for PyGame
or Tkinter
individually:
import pygame
import Tkinter as tk
window = tk.Tk()
pygame.init()
pygame.mixer.music.load("music.mp3")
False
:
started = False
playing = False
playing
and started
variables global so that the function can change their values:
def buttonClick():
global playing, started
if not playing:
if not started:
pygame.mixer.music.play(-1)
started = True
else:
pygame.mixer.music.unpause()
button.config(text="Pause")
else:
pygame.mixer.music.pause()
button.config(text="Play")
True
(it was playing), it will be swapped to False
(stops playing) and vice versa.
playing = not playing
volume_set()
function requires a number between 0 and 1. For that reason, the last statement in this function divides the slider’s value by 100 so that it is the right size:
def setVolume(val):
volume = float(slider.get())
pygame.mixer.music.set_volume(volume / 100)
Tkinter
button and a Tkinter
scale object are used. While it’s possible to make these things in PyGame
, they have already been built into Tkinter
to make it much quicker and easier for you to use them:
slider = tk.Scale(window, from_=100, to=0, command=setVolume)
button = tk.Button(window, text="Play", command=buttonClick)
Tkinter
main loop:
slider.pack()
slider.set(100)
button.pack()
window.mainloop()
In Adventure 8, you created a very basic game where a sprite walks around the window. With a few slight changes to the program, you can add music and sounds, which will add sophistication and polish to your game.
In this program, you’ll modify the sprite walking program to add background music and a sound effect when the sprite teleports.
walkingSprite.py
.white = pygame.color.Color("#FFFFFF")
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play(-1)
teleportSound = pygame.mixer.Sound("teleport.wav")
if count < 5:
image = teleport1
elif count < 10:
image = teleport2
if
statement so that the sound only plays once at the start of the loop:
if count == 0:
teleportSound.play()
else:
x = random.randrange(0, windowSize[0])
y = random.randrange(0, windowSize[1])
count = -1
locked = False
count += 1
Python Command Quick Reference Table |
|
Command |
Description |
|
This function is used to load a sound. The filename of the sound is used as an argument. Once the file is loaded, it can be stored in a variable. |
|
To play a sound that has been loaded using the |
|
Instead of you having to import the time module to use with |
|
This function returns the length of a sound in seconds. By dividing it by 1000, you can convert it to milliseconds. |
|
The modulo operator divides one number by another and returns the remainder from the division. |
|
In |
|
This function is used to play a loaded music file. If you use -1 as an argument, the music will repeat forever. |
|
When music is playing, this function will return |
|
The |
|
This function is used to set the volume of the |
Achievement Unlocked: Skilled manipulator of sound and music in Python and PyGame
programs.