the basics of sound in p5js

All of the documentation for sound-related functions in p5js is here: https://p5js.org/reference/#/libraries/p5.sound

Let's get a sound playing in p5js.

This works, but notice the problem when you click the square more than once!

This one plays two sound files simultaneously. There are a few other things it does, which you should try to disable so that you can understand how it works. Try disabling one of the sounds. It also uses a randomized start time for the second of the sound files. Also notice that it pauses the loop when the mouse is released; that means that the loop starts from where it left off when the button is re-pressed. A different possible behaviour is for the loop to restart. Can you look at the documentation and figure out how to do that?

Also, can you figure out why it sounds like two different sound files even though it only uses one? What's been done in the second call to loop that makes it different?

Notice the terrible clicking that happens when you stop pressing the mouse button. There's not proper envelope for the sound. That sudden drop from some amplitude to 0 makes the click. One way to fix that might be this:

In this version, we use setVolume and give pause an argument to tell it to pause AFTER the fade-out.

This version is a little nicer in some ways; it loops while you press the box, but the looping stops once you stop pressing the mouse. We accomplish that by passing false to setLoop.

After your add your sound in the editor, be sure to save the drawing. My sound didn't load until I did so.

Be sure to add the file extension in the file name. I didn't and got a difficult-to-interpret error.

Use mp3s or ogg so that they load more quickly. For more on file formats, see this expanding page: https://renickbell.net/doku.php?id=sound-file-formats

  • p5js-sound1.txt
  • Last modified: 8 weeks ago
  • by renick