Playing sounds and music

pyglet makes it easy to play and mix multiple sounds together in your game. The following example plays an MP3 file [5]:

import pyglet

music = pyglet.resource.media('music.mp3')
music.play()

pyglet.app.run()

As with the image loading example presented earlier, pyglet.resource.media locates the sound file in the application's directory (not the working directory). If you know the actual filesystem path (either relative or absolute), use pyglet.media.load.

Short sounds, such as a gunfire shot used in a game, should be decoded in memory before they are used, so that they play more immediately and incur less of a CPU performance penalty. Specify streaming=False in this case:

sound = pyglet.resource.media('shot.wav', streaming=False)
sound.play()

The examples/media_player.py example demonstrates playback of streaming audio and video using pyglet. The examples/noisy/noisy.py example demonstrates playing many short audio samples simultaneously, as in a game.

[5]MP3 and other compressed audio formats require AVbin to be installed (this is the default for the Windows and Mac OS X installers). Uncompressed WAV files can be played without AVbin.