3

I've used the code below, (which I found online) to make audio play when a button is clicked on my site, and now I'm curious what I can do to make the audio pause and/or stop playing when that same button is clicked with similar code?

const rollSound = new Audio("./mp3/SoItGoes.mp3");
$('#Triangle').click(e => rollSound.play());
  • If this work for you? https://stackoverflow.com/questions/2988050/html5-audio-player-jquery-toggle-click-play-pause/2988130#2988130 – yinsweet May 17 '20 at 00:39
  • `rollSound.pause` (https://www.w3schools.com/jsref/met_audio_play.asp) is how you stop a sound. – user2740650 May 17 '20 at 00:39

2 Answers2

3

You can use a class on the button that specifies the state of the player (class = "playing" if it's playing, nothing if it's paused, initiated to nothing), and check it when the button is clicked:

HTML:

<button id="Triangle">Play/Pause</button>

JavaScript:

$('#Triangle').click(function(e) {
    if ($(this).hasClass('playing')) {
        rollSound.pause();
        $(this).removeClass('playing');
    } else {
        rollSound.play();
        $(this).addClass('playing');
    }
});
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

You might use an if statement in your event handler to check for the button text value, you can use something like this:

HTML:

<button id="Triangle">Play</button>

JS:

const rollSound = new Audio("./mp3/SoItGoes.mp3");
$('#Triangle').click((e) => {
  if($('#Triangle').text() === 'Play') {
      rollSound.play();
      $('#Triangle').text('Pause')
  }
  else {
    rollSound.pause();
    $('#Triangle').text('Play')
  }
});
ROOT
  • 11,363
  • 5
  • 30
  • 45