Pygame modules for interactive programs

Sound

Pygame handles sound effects via its mixer module. The primary file formats are WAV or OGG. Think of sound effects as sounds that accompany actions in a game (e.g., jumping, punching, flying, phone ringing). Sound effects can be layered so that multiple sound effects play at once, or even the same sound plays more than once simultaneously.

Pygame also includes capabilities for background music from OGG and MP3 files. The main difference between sounds and music beyond file format is that only one track per device can be playing at a given time.

Sound Module

To play a sound effect, I create a pygame.mixer.Sound object. The only argument is the file name of the WAV or OGG file to load. Once I create the object, I access it directly to play or adjust the sound (see also the "Playing a Sound More than Once" box). The soundPlayer.py program (Listing 7) demonstrates the most common sound functions. Note that all functions occur in the object mySound.

Playing a Sound More than Once

Pygame sound objects can be played more than once without reinitializing or reloading. For instance, if the springy jump sound is loaded in the jumpSound object, it can be played simply by calling jumpsound.play() in conjunction with the jump() function elsewhere in the game logic, even if the sound from a previous jump is still playing. Pygame handles overlaps automatically, and each playback will run to its natural conclusion (end of the sound file).

There are a few caveats to this however. Any call to stop(), fadeout(), or set_volume() will affect all instances of the playing sound. If my hero character jumps into a lava pit and dies, then I can stop all of the jump sound effects just by calling jumpSound.stop() once.

If, however, I need to control the volume or the playback start and stop on the same sound effect separately (perhaps to simulate location or distance from the player), then I need to load each version of the sound in a separate object, even though they are the same sound.

To see this behavior in action, run the soundPlayer.py example and press p multiple times!

Listing 7

A Sound Object

01 import pygame
02
03 pygame.mixer.init()
04 pygame.display.init()
05
06 screen = pygame.display.set_mode ( ( 320 , 240 ) )
07 mySound = pygame.mixer.Sound ( "Mists_of_Time-4T.ogg" )
08
09 running = True
10 volume = 1.0
11
12 while running:
13    for event in pygame.event.get():
14       if event.type == pygame.QUIT:
15          running = False
16       elif event.type == pygame.KEYDOWN:
17          if event.key == ord ( "p" ):
18             mySound.play()
19          elif event.key == ord ( "s" ):
20             mySound.stop()
21          elif event.key == ord ( "f" ):
22             mySound.fadeout ( 2000 )
23          elif event.key == pygame.K_DOWN:
24             volume -= 0.05
25             if volume < 0: volume = 0.0
26             mySound.set_volume ( volume )
27          elif event.key == pygame.K_UP:
28             volume += 0.05
29             if volume > 1: volume = 1.0
30             mySound.set_volume ( volume )

Stepping through the example, lines 1-6 are the standard Pygame initialization that I've used in the past. Note that line 3 specifically initializes the pygame.mixer module. I'm also initializing a graphics window, even though I don't have any graphics functions.

Line 7 loads the OGG file – I got mine from vorbis.com [3]. Once the sound is loaded, I access it via the variable mySound.

In lines 9 and 10, I set up the state variables: the running flag indicates whether or not to continue the event loop, and volume is the volume of the sound effect.

Lines 12 and 13 start the event loop that I've used in other examples, lines 14 and 15 check for the pygame.QUIT event, and then lines 16 onward handle key presses to make the sound player do its thing.

Lines 17 and 18 plays the sound (mySound.play()) if p is pressed. If I provide a number to the play argument, the sound will loop that many times more: loops do NOT count the initial play. Therefore, a loop value of 1 will play the track twice, a value of 499 will make it play it 500 times, and so on.

The sound playback stops immediately if the s key is pressed (lines 19 and 20). This only affects the current object. Other sounds will continue to play. If f is pressed, the sound fades over the provided number of milliseconds (lines 21 and 22). In this example, the sound fades out over 2,000 milliseconds, or two seconds.

If the down arrow is pressed the volume decreases by 5 percent (lines 23-26), and if the up arrow is pressed, the sound increases by 5 percent (lines 27-30). Before setting the volume with mySound, I make sure volume does not go below zero (line 25) or above one (line 29). Pygame volume is set by a float between 0 and 1, where 0 is off and 1 is full volume.

Buy this article as PDF

Express-Checkout as PDF

Pages: 2

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content