Submodule 18.3: Sound in p5.js
Submodule 18.3: Sound in p5.js
- load and play sound
- play and pause buttons
- capture sound
load and play sound
p5.js has a build-in p5.js sound library which enables us to manipulate sound.
In order to load sound, we use the loadSound() function.  Similar to other media, we put this function inside the preload().
To actually play the sound we should use the play() function. 
Moreover, we can adjust the sound level by using the setVolume() function. This function takes values from 0.0 (minimum) to 1.0 (maximum).
Let's see an example of how the above should look like in the code.
Example
Here is an example code where we load and play a sound:
function preload() {
 mySound = loadSound('sounds/Sg.mp3');
}
function setup() {
  // define the sound level
  mySound.setVolume(0.1);
  // play the sound
  mySound.play();
}
You can see the result of the above code here
Exercise
- Open your Visual Studio editor and the p5yourNamefolder.
- Open the file ex812.jsin your editor and save it asex1031.js
- Open the file ex812.htmlin your editor and save it asex1031.html
- In the ex1031.htmlfile, update the link toex1031.jsfrom exersice812.js
-  Go to the index.htmlfile and create, underModule 10, alinkto theex1031.htmlfile with the title "load and play sound".
Modify the ex1031.jsfile and use as a base the above example to load a sound. The sound volume should increase as long as the mouse is pressed and when released, should return to the original volume. You can see here an example.
function preload() {
 mySound = loadSound('sounds/Sg.mp3');
}
function setup() {
  // define the sound level
  mySound.setVolume(0.1);
  // play the sound
  mySound.play();
}
function mousePressed() {
  // increase sound level when mouse is pressed
  mySound.setVolume(0.5);
}
function mouseReleased() {
  // return to the original sound level
  mySound.setVolume(0.1);
}
Do a Git commit with the message "load and play sound".
- See more about the loadSound() function
- See more about the play() function
- See more about the setVolume() function