Operation Manual
Experiments in Python
98
Notes:
Making a noise
Graphics are all well and good, but if we are going to create true multimedia
software then we’re going to need to master audio output as well. Let’s see if we
can add some sounds to our programs.
import numpy
import wave
import pygame
# sample rate of a WAV le
SAMPLERATE = 44100 # Hz
def createSignal(frequency, duration):
samples = int(duration*SAMPLERATE)
period = SAMPLERATE / frequency # in sample points
omega = numpy.pi * 2 / period
xaxis = numpy.arange(samples, dtype=numpy.oat) * omega
yaxis = 16384 * numpy.sin(xaxis)
# 16384 is maximum amplitude (volume)
return ya xis.asty p e('int16').t o s t r i n g()
def createWAVFile(lename, signal):
le = wave.open(lename, 'wb')
le.setparams((1, 2, SAMPLERATE, len( s i g n a l ), 'NONE',
'noncompressed'))
le.writeframes(signal)
le.close()
def playWAVFile( l e n a m e ):
pygame.mixer.init()
sound = pygame.mixer.Sound(lename)
so u n d.play()
# wait for sound to stop playing
while p y g a m e . m i x e r.g e t _ b u s y( ):
pass
# main program starts here
lename = '/tmp/440hz.wav'
signal = createSignal(frequency=440, duration=4)
createWAVFile(lename, signal)
playWAVFile(lename)
Playing sounds on a computer simply means taking data from a file, converting it
to waveform data and then sending that to hardware that converts the waveform
into an electrical signal, which then goes to an amplifier and loudspeaker.
On the Raspberry Pi, PyGame can be used to play sounds from a file. Rather than
provide a file with some sound on it, we will generate a file with the data within it
to play sound. You probably know that sound is actually the compression and
rarefaction (stretching) of air to cause your eardrum to move.