Search code examples
jqueryhtmleventshtml5-audiopause

How to differentiate human and programatically triggered audio pause event


So, what I am trying to achieve is that when users click on A elements, a bootstrap modal window shows up and pauses any audio that is playing. After the modal is closed, audio should be resumed.

This is the code I've been using, to no avail:

playingaudio = false; // global variable

$(document).on("click", "a", function(){

if (playingaudio && $('#audioplayer').length) {
  $('#audioplayer')[0].pause(); // pause audio programatically
  playingaudio = true;
}

// show modal code

});

$('#myModal').on('hidden.bs.modal', function () {
// if there is an audioplayer and it is paused, resume playback
if (playingaudio && $('#audioplayer').length) {
   $('#audioplayer')[0].play();
}

});

$('#audioplayer').on('play', function() {
  playingaudio = true;
});

$('#audioplayer').on('pause', function(e) {
  playingaudio = false;
});

Strangely enough, this code works if I set up a breakpoint in the "playingaudio = true" line inside the A onclick event handler, but when executed without breakpoints, it fails to do what is meant to.

Any ideas on how to make this work?


Solution

  • OK, so I finally solved it! I share the answer with you guys. Thanks for all your great help!

    <audio controls id='audioplayer'>
    <source src='http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3' type='audio/mpeg'>
    Your browser does not support the audio element.
    </audio>
    
    <div>
      <div>
        <span>Playing Mode: </span>
        <span class='playing_mode_label'></span>
      </div>
      <br>
      <a href="#">a button</a>
      <br>
      <button class='fake_modal'>fake modal - click to close</button>
    </div>
    
    $('.fake_modal').hide();
    
    $(document).on("click", "a", function() {
    var audioplayer = $('#audioplayer');
    
    if (audioplayer.length) { // if there is an audioplayer
      if (!audioplayer.prop('paused') && audioplayer.prop('currentTime')) {
        audioplayer.trigger('pause'); // pause audio
        playingaudio = true;
      } else {
        playingaudio = false;
      }
    }
    
    $('.fake_modal').show(); // show modal
    
    });
    
    $('.fake_modal').on('click', function() {
        $('.fake_modal').hide();  //hide modal
      var audioplayer = $('#audioplayer');
        if (playingaudio && audioplayer.length) { // if there is an audioplayer
            audioplayer.trigger("play");
        }
    
    });