Raspberry_Pi_Education_Manual

Notes:

That “action” is stored in a computer as numbers ranging from some large negative number to the same positive number, say 16,384 (2 14 – remember your binary!), for a particular duration of time, say 4 seconds. If we move up and down that range evenly, say, 440 times each second, and pass those numbers to the sound hardware in the Raspberry Pi, we should hear the musical note “A”, above middle C.

The sin() function returns a numeric value between -1 and +1, which represents the sine of the parameter entered between the brackets.

The evenness of this movement is given by the mathematic function we saw earlier, called sine, which when given an angle ranges from -1 to +1 for every 180 degrees. Given the full 360 degrees it goes from -1 to +1 and then back to -1 again. This gives the peaks and troughs. The “sin” function in Python doesn’t use degrees, it uses “radians”. There are 2π radians in 360 degrees. We can’t just pass 440 peaks and troughs every second because we’d miss out all those values in-between. In the digital music world, CDs and MP3s send out 44,100 numbers to get the numbers in-between each second of sound. We can do that too, and this gives us the sampling rate of the music. Holding a lot of data in Python can be inefficient, so some clever solutions for holding numbers can be found in a library called “numpy”. The first “arange” generates a long list of consecutive numbers – 44,100 for each second of music. Each is a point in time of each sample of sound. The “sin” function takes the list of numbers, adjusted by omega for the correct frequency, and gives a list of numbers representing the movement of the air for each point in time.

This list of sounds can then be saved to a file in a particular wave format. Finally, that sound wave can be played in the sound mixer in PyGame.

Normally, you wouldn’t generate sounds and then play them immediately. Sound files such as these would be created in advance, and only played within your own programs when required. However, if you were developing a sound-manipulation program, you would need to create and manipulate the sound data directly, a little like this. There are better methods of doing this that do not require writing to a file, which you might think about.

Experiments in Python

99

Made with FlippingBook flipbook maker