A good game needs to have great music and sound effects. The Pygame mixer
module lets us play a sound or any audio for that matter.
We will download a WAV audio file using standard Python. We will play this sound when the game quits. This example requires you to actually execute the example code, because this book has no audio support.
Sound
object after specifying the name of the audio file. This class as you would expect embodies the concept of sounds:audio = pygame.mixer.Sound(WAV_FILE)
Sound
object has a play
method, which has a number of loops parameters. If the value of this parameter is set to -1, the sound will loop indefinitely:audio.play(-1)
pygame.time.delay(TIMEOUT * 1000)
The delay is specified in milliseconds, that's why we are multiplying by 1000.
stop
method:audio.stop()
The audio demo code is listed as follows:
import pygame, sys from pygame.locals import * import numpy import urllib2 import time WAV_FILE = 'smashingbaby.wav' def play(): audio = pygame.mixer.Sound(WAV_FILE) audio.play(-1) TIMEOUT = 1 pygame.time.delay(TIMEOUT * 1000) audio.stop() time.sleep(TIMEOUT) pygame.init() pygame.display.set_caption('Sound Demo') response = urllib2.urlopen('http://www.thesoundarchive.com/austinpowers/smashingbaby.wav') filehandle = open(WAV_FILE, 'w') filehandle.write(response.read()) filehandle.close() screen = pygame.display.set_mode((400, 400)) while True: sys_font = pygame.font.SysFont("None", 19) rendered = sys_font.render('Smashing Baby', 0, (255, 100, 100)) screen.blit(rendered, (100, 100)) for event in pygame.event.get(): if event.type == QUIT: play() pygame.quit() sys.exit() pygame.display.update()
The most important functions of this demo are summed up in the following table:
Function |
Description |
---|---|
|
This function creates a |
|
This function plays and loops indefinitely (-1 means indefinitely). By default the sound is played only once. This corresponds with 0 loops. If the value is 2, the sound will be played once and then repeated 2 more times. |
|
This function pauses the game for a specified number of milliseconds. |
|
This function stops audio playback. |