Sound in Python

Sound is an essential component of digital media. Proof? Almost nobody watches silent films anymore, and nobody makes them. Video games are rarely played with the sound turned off. There are a few important reasons for this.

  1. Much human communication is through sound. Speech is the best ex­ample, but non-speech sounds, clapping, or stamping of feet are ways that people make their feelings and intentions known.
  2. Sounds are associated with events. When an object falls to the floor, a sound occurs with the impact. A button is pressed and a doorbell rings. These sounds are important indicators.
  3. Sounds cause emotional reactions in people. Music can do this; it can convey a mood better than almost anything else. But sound can also indicate things unseen: a growling in the dark; a screech in the sky; and the sound of an approaching vehicle around a curve in the road.

In Pygame, a sound is much like an image in terms of how it is used. A sound file is loaded and assigned to a variable, then that variable can be used to play, stop, rewind, and perform all audio operations on that sound. Each sound must be loaded into a distinct variable and has its own controls. The paradigm for sounds should therefore seem familiar.

The main sub-system in Pygame that deals with sound is named mixer. The first step in playing a sound is to create a mixer object and then use it to load the file. The function pygame.mixer.Sound(s) is used for this, passing the name of the sound file:

m = pygame.mixer.Sound(“song.wav”)

Playing the sound is done using the mixer method play:

m.play()

Example: Play a Sound

It’s simple. A program that loads and plays a sound file is only 10 lines long:

import pygame

screen = pygame.display.set mode((300, 300))

pygame.init()

FPS = 10

m = pygame.mixer.Sound(“song.wav”)

m.play()

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

quit()

Stopping a sound from playing is a matter of calling m.stop(). Setting the volume means calling m .set_volume (v) where the volume parameter v is be­tween 0.0 and 1.0, where 0.0 is no sound and 1.0 is maximum volume. That’s pretty much it for the basics.

Example: Control Volume Using the Keyboard

This example adds a volume control. The function keypressed() modifies the volume of the audio playback using the set_volume function. It changes the volume level by an increment each time the key “w” is pressed, and decreases it when the “s” key is pressed. The new program is as follows:

def keyPressed(k):

global volume, m

if k.key == pygame.K w:

volume = volume+.l

elif k.key == pygame.K s:

volume = volume-.1

if volume<0: volume = 0

if volume>1: volume = 1 m.set

volume(volume)

print (volume)

screen = pygame.display.set mode((300, 300))

pygame.init()

FPS = 10

m = pygame.mixer.Sound(“song.wav”)

m.play()

volume = 1.0

m.set volume(volume)

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

quit()

if event.type == pygame.KEYDOWN:

keyPressed (event)

Example: Play a Sound Effect at the Right Moment: Bounces

A sound effect represents some event, and needs to be played at the moment the event happens. Synchronizing the two things is as simple as playing a sound when the event is detected. This example program plays a sound representing a ball hitting something when a simulated ball hits the side of the window and bounces. The bouncing ball animation program provides the impact event: when the ball hits the side of the window, the sound of an impact is played.

The sound effect is a file, and was recorded using an inexpensive micro­phone, a computer with a sound card, and the Audacity software, which is free and downloadable (see the end-of-chapter resources). The sound of a glass hitting a desk was recorded, edited, and saved as a “.wav” file named “bounce.wav.” The program was modified to read that file, and then play it back whenever a collision with the window was detected. The program has three new lines of code, includ­ing the reading of the file:

In many situations, there can be a small delay between the event and the sound being played. A sound can rarely be played instantaneously.

Music

The mixer.Sound module is fine for many purposes, including playing mu­sic, but sometimes music has special needs and properties. Normally, only one music selection is played at a time. Sometimes, music needs to be paused and later restarted. For playing music, Pygame has a special module named pygame. mixer.music that has a different interface. First, there are no instances that are returned. Playing a song means loading it and then playing it like this:

pygame.mixer.music.load(“song.wav”)

pygame.mixer.music.play()

From this point on, references through pygame.mixer.music will affect the song that is playing. As before, the volume can be changed between 0 and 1:

pygame.mixer.music.set volume(volume)

However, now the song can be paused and restarted:

pygame.mixer.music.pause()

pygame.mixer.music.unpause()

We can determine where the is playing at the moment, in milliseconds from the start, or set the posit at which it is to play:

pygame.mixer.music.get_pos ()

pygame.mixer.music.set_pos (i)

There are other features documented at the Pygame website (https://www. pygame.org/docs/ref/music.html). A simple keyPressed function that allows the volume to be changed (“w” and “s”) and the music to be paused and resumed (“p” and “r”) is as follows:

def keyPressed(k): global volume

if k.key == pygame.K w:

volume = volume+.l

pygame.mixer.music.set volume(volume)

elif k.key == pygame.K s:

volume = volume-.1

pygame.mixer.music.set volume(volume)

elif k.key == pygame.K p:

pygame.mixer.music.pause()

elif k.key == pygame.K r:

pygame.mixer.music.unpause()

Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *