Matthew Pichola
Matthew Pichola

Reputation: 77

How can I pause music on click?

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());

Upvotes: 3

Views: 877

Answers (2)

Djaouad
Djaouad

Reputation: 22776

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');
    }
});

Upvotes: 3

ROOT
ROOT

Reputation: 11622

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')
  }
});

Upvotes: 0

Related Questions