Sound in Python

[ LiB ]

Sound in Python

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

  • PythonWare Sound Toolkit. An ( unfortunately ) abandoned kit for reading and playing AU, VOC, and WAV files on Windows and Sun OSs. The unfinished tookit is still available from PythonWare at

    PythonWare is a copyrighted , but free to use, library.

  • Boodler. An interesting tool for creating soundscapes which uses Python and is created for UNIX operating systems (although some work on PDAs, Mac, and with Direct X has been done). The project can be found at

    Boodler combines sound samples into an ongoing stream of sound for background noise.

  • The Snack Toolkit. The Snack Toolkit was developed by Kare Sjolander for TCL and Python. It is a sound-processing toolkit with a TK interface. It supports MP3 and sound filtering; the idea behind the kit is rapid development. Snack needs both Tkinter and Tcl/Tk to work correctly. It adds the snack:sound command, which is used to create and handle sound objects, read audio data from wav files, and play sounds. Snack is accessed using the tkSnack module. You can find information on Snack at

  • The MusicKit Library. MusicKit is a full, object-oriented library for signal processing and building sound, music, and creating MIDI applications. The kit is based on Music V (From Bell Labs and Max Mathews) and was originally written for NeXT. These are C tools made available to Python using PyObjC or the Objective-C bridge. The DSP tools are only portable to Intel systems or m68k, but the MIDI and sound streaming are available on Windows and Mac platforms (at the time of this writing the project team was still working on a port to Linux). The kit can be found on its own Sourceforge page, along with on-line documentation, code examples, utilities, applications, and musical scores at http://musickit. sourceforge .net/.

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




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


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


An interface to the Sun AU sound format


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


Reads EA IFF chunks


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




The sound parameter is the name of a WAV file


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


Play the sound repeatedly


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


Stop playing a specified sound


Allows sounds to play asynchronously


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


Do not interrupt sounds currently playing


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 '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') 

That's it. To get this code to run on its own (as the 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 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 ]

Game Programming with Pyton, Lua and Ruby
Game Programming with Pyton, Lua and Ruby
Year: 2005
Pages: 133 © 2008-2017.
If you may any questions please contact us: