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

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex1031.js
  3. Open the file ex812.html in your editor and save it as ex1031.html
  4. In the ex1031.html file, update the link to ex1031.js  from exersice812.js
  5. Go to the index.html file and create, under Module 10, a link to the ex1031.html  file 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.

Answer:

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".