Playing Sound Files Repeatedly
This post is part of a series of notes and exercises for a summer camp on making musical instruments with Arduino and Pure Data.
In an earlier exercise, we created an abstraction to read in a sound file and play it. If you plan on playing the sound more than once, it doesn’t make a lot of sense to read it in each time. It repeats work unnecessarily, and reading from the computer’s hard drive can be slow.
Rather, we should separate the reading from the playing. Then we can read it once into the computer’s memory (RAM), which is must faster to access than disk, and play it as many times as we like.
Let’s design a new abstraction for doing the reading. We’ll call it load_sound_file
. It needs to know two things: the file to read and the array to drop the sound data into. We’ll send it a message containing these two pieces of information. Here, for example, we read in song.wav
and store it in the array clip
:
We click on the loading message just once. The array will store the sound wave. Then we click on the bang as many time as we like to play it back.
How do we define load_sound_file
? Recall that soundfiler
responds to a read -resize PATH ARRAY
message. If a list arrives at a message’s inlet, the list’s elements can be referenced within the message using $1
, $2
, and so on. So, we turn the PATH ARRAY
message passed to the abstraction into a list and pass it to the read
message. The soundfiler
then does the hard work. All told, our abstraction looks like this: