Raspberry_Pi_Education_Manual

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 file 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.float) * omega yaxis = 16384 * numpy.sin(xaxis) # 16384 is maximum amplitude (volume) return yaxis.astype( 'int16' ).tostring() def createWAVFile (filename, signal): file = wave.open(filename, 'wb' ) file .setparams((1, 2, SAMPLERATE, len (signal), 'NONE' , 'noncompressed' )) file .writeframes(signal) file .close() def playWAVFile (filename): pygame.mixer.init() sound = pygame.mixer.Sound(filename) sound.play()

# wait for sound to stop playing while pygame.mixer.get _ busy(): pass

# main program starts here filename = '/tmp/440hz.wav' signal = createSignal(frequency=440, duration=4) createWAVFile(filename, signal) playWAVFile(filename)

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.

Experiments in Python

98

Made with FlippingBook flipbook maker