Submodule 18.3: Sound in p5.js

play and pause buttons

In order to control whether our sound will play or pause we can create a button which will pause the sound if it is playing and make it play if it is not.

We have already see how we can make a sound play. In order to make it pause we use the pause() function.

However, how we can detect whether a sound is playing?

p5.js has the isPlaying() function. This function returns a boolean value which is true if the sound is playing and false if it is not.

Let's see how we can use it to play/pause our song.

Example 

Here is an example code where we use a button to play/pause a sound:

// create a variable for the button
let myBtn;
function preload() {
 mySound = loadSound('sounds/Sg.mp3');
}

function setup() {
  createCanvas(200,200);
  // create the button to control sound
  myBtn = createButton('play');
  // call the function playPause when the user presses the mouse
  myBtn.mousePressed(playPause);
}
function playPause(){
  //use the isPlaying to determine whether the sound is playing or not
  // if the sound is not playing
  if (!mySound.isPlaying()){
    // make it play
    mySound.play();
    // define the sound level
    mySound.setVolume(0.5);
  }
  // else pause it
  else {
    mySound.pause();
  }
}

You can see the result of the above code here. This example works best in mozilla firefox.

Exercise

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex1032.js
  3. Open the file ex812.html in your editor and save it as ex1032.html
  4. In the ex1032.html file, update the link to ex1032.js  from exersice812.js
  5. Go to the index.html file and create, under Module 10, a link to the ex1032.html  file with the title "play and pause buttons".

Modify the ex1032.jsfile and use as a base the above example and load a sound which will start from the beginning each time the user presses the button. To do this you should use the stop() function for which you can learn more here. You can see here an example.

Answer:

// create a variable for the button
let myBtn;
function preload() {
 mySound = loadSound('sounds/Sg.mp3');
}

function setup() {
  createCanvas(200,200);
  // create the button to control sound
  myBtn = createButton('play');
  // call the function playPause when the user presses the mouse
  myBtn.mousePressed(playPause);
}
function playPause(){
  //use the isPlaying to determine whether the sound is playing or not
  // if the sound is not playing
  if (!mySound.isPlaying()){
    // make it play
    mySound.play();
    // define the sound level
    mySound.setVolume(0.5);
  }
  // else stop it
  else {
    mySound.stop();
  }
}


Do a Git commit with the message "play and pause buttons".