[ LiB ]Python GraphicsNetworking in Python

Sound in Python

Like with graphics, there are a number of available libraries for implementing sound in Python.

Python, of course, comes with a few sound functions built-in. These are included under Multimedia Services and listed in Table 4.27.

Table 4.27. Python Multimedia audio Services

Module

Use

audioop

Manipulates raw audio data.Operates on sound fragments consisting of signed integer samples 8, 16, or 32 bits wide, stored in Python strings

aifc

Reads and writes audio files in AIFF or AIFC format (Audio Interchange File Format)

sunau

An interface to the Sun AU sound format

wave

An interface to the WAV sound format. Supports stereo and mono but not compression and decompression

chunk

Reads EA IFF chunks

sndhdr

Provides utility functions that determine the type of a sound file


Python also possesses a Winsound module that provides access to the basic sound-playing machinery on Windows platforms. Winsound includes a single function from the platform API, PlaySound, which takes in a sound parameter argument that can be either a filename, a string (that's a string of audio data) or None.

Winsound's flags are listed in Table 4.28.

Table 4.28. Windsound's Flags

Flag

Purpose

SND_FILENAME

The sound parameter is the name of a WAV file

SND_ALIAS

The sound parameter should be interpreted as a control panel sound association name

SND_LOOP

Play the sound repeatedly

SND_MEMORY

The sound parameter to PlaySound() is a memory image of a WAV file

SND_PURGE

Stop playing a specified sound

SND_ASYNC

Allows sounds to play asynchronously

SND_NODEFAULT

If the specified sound cannot be found, do not play the default beep

SND_NOSTOP

Do not interrupt sounds currently playing

SND_NOWAIT

Return immediately if the sound driver is busy


Although loading and playing sounds is covered in this section, audio programming and the science behind sound waves is a complex and in-depth field. If you find audio programming to be your bliss, I suggest checking out a copy of Mason McCuskey's Beginning Game Audio Programming from your local library.

Playing a Sound with Pygame

You can play a sound using Python Pygame with just a few short lines of code. First do the typical pygame import and the os module import so that you can find files on the native operating system:

# Import necessary modules import os, pygame from pygame.locals import *

After importing the needed libraries, you initialize pygame:

pygame.init()

Pygame 's cross-platform music tools for sound effects and music are built through the mixer module, so you use pygame.mixer to load the sound, and the built-in play() method to play it:

sound1 = pygame.mixer.Sound('JUNGLE.wav')
sound1.play()

That's it. To get this code to run on its own (as the Play_Sound.py sample in the Chapter 4 code section on the CD does), you also need to add a loop that keeps the program running so that the sound has time to be loaded and played:

while 1: pass

Viola! Instant sound with only six small lines of code! Not bad at all. Of course, a real game will need a sound function that's a bit more versatile.

Building a load_sound Function

A Pygame load_sound function would look very similar to the load_image function you created at the beginning of this chapter. You start by defining the function, which takes in the name of the sound file:

def load_sound(name):

The load_sound code should check to see if pygame.mixer (the Pygame module that loads up sounds) is installed. If pygame.mixer isn't available, Pygame will not be able to load the sound. Pygame has a built-in feature called Nonesound, which, if used, will send a blank sound object if the file cannot be found, so your function will not crash while trying to load a non-existent sound.

if not pygame.mixer:
 return NoneSound()

Next, as with load_image, you build the complete path to the object with the os module:

fullname=os.path.join('data', name)

Then use a try/except clause and return the sound object:

try:
 sound=pygame.mixer.Sound(fullname)
except pygame.error, message:
 print 'Cannot load sound:', wav
 raise SystemExit, message
 return sound

The full snip can be found as Load_Sound.py on the CD:

def load_sound(name):
 class NoneSound: 
 def play(self): pass
 if not pygame.mixer:
 return NoneSound()
 fullname=os.path.join('data', name)
 try:
 sound=pygame.mixer.Sound(fullname)
 except pygame.error, message:
 print 'Cannot load sound:', wav
 raise SystemExit, message
 return sound

[ LiB ]Python GraphicsNetworking in Python