Andy James Andy James - 5 months ago 22
CSS Question

jQuery to pause and play audio and change icons

I am trying to play an MP3 file on my webpage, but would like to use an option for the user to choose whether to play the music or not. So I need a button to toggle between play and stop.

HTML

<li><a href="#" id="music"><i class="fa fa-music fa-2x" aria-hidden="true"></i></a></li>


JavaScript

$("#music").click(function() {
//$("blockquote").removeClass("animated rollIn").addClass("animated hinge");
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/om_cut.mp3');

audioElement.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);

audioElement.play();
$(this).find('i').toggleClass('fa-music fa-stop');
});


So I am able to play the music successfully on click and when I tap on the play icon, my icon also changes to the stop icon.

But I want that when I click on the stop icon, the music stops and the icon changes back to the play icon. I am not able to understand how to add the second click event to this icon.

Answer

Try this:

var playing = false;
var initDone = false;

var audioElement = null;

$("#music").click(function() {
  if (playing) {
    // Stop playing
    audioElement.pause();
  } else {
    // Start playing
    if (!initDone) {
      initDone = true;

      audioElement = document.createElement('audio');
      audioElement.setAttribute('src', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/om_cut.mp3');

      audioElement.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
      }, false);
    }

    audioElement.play();
  }

  $(this).find('i').toggleClass('fa-music fa-stop');
  playing = !playing;
});