First thing we have to do is write a new
script element to attach the new sound library:
<script src="p5.min.js"></script> <script src="p5.sound.js"></script> <script src="sketch.js"></script>
Now we can load a sound file and play it in a p5 sketch.
Getting or creating sounds can be done in many ways.
Freesound.org is a great resource for sound recordings available under the Creative Commons license.
Free Music Archive is a great resource for musical recordings in many genres, many using the Creative Commons license.
One of my favorite tools is jfxr, which is a web application ported from sfxr, a program designed to generate 8-bit style sound effects. There a version for Apple called cfxr if you want to download the software.
Once you have generated a sound you like, add it to the folder with
Like images, the sound file should be preloaded.
Here's a simple sketch to play a sound.
Let's add some background music and play with a few parameters to see other things we can do with the p5 sound library. First I'll download a track from the Free Music Archive and load it in my sketch.
var vol = map(mouseY, 0, height, 1, 0); music.setVolume(vol);
We can also pan the stereo field of the track using pan. Let's map pan to x:
var pan = map(mouseX, 0, width, -1, 1); music.pan(pan);
We can also change the rate of playback. This time we'll map playback rate of the track to the mouse position.
var rate = map(mouseX, 0, width, 0.5, 4); music.rate(rate);
This is just a small sample of everything that can be done with the sound file.