Double Tap to Play or Pause the WordPress Audio Player on Touch Devices

Plugin:

Wonder Audio Player

Tutorial:

In the tutorial Use the Space Key to Play or Pause the WordPress Audio Player, we learned how to use the space key to control the audio player. However, on touch devices, there isn't a keyboard available. This tutorial will guide you on how to play or pause the WordPress audio player on touch devices by double-tapping the webpage in mobile web browsers. This tutorial also provides code to support double-click on regular desktop and laptop computers.

An online demo is as follows:

To support double-tap on mobile touch devices, edit the player in the Wonder Audio Player plugin. Navigate to the 'Options' tab, then to 'Advanced Options,' and add the following code to the 'Custom JavaScript' input box:

(function($){
  $(document).ready(function() {
    var timeDiff = 500;
    var lastClick = 0;
    var startEvent = "touchstart";
    $(document).on(startEvent, function() {
      var clickTime = Date.now();
      var obj = $("#wonderpluginaudio-AUDIOPLAYERID").data("object");
      var eventFired = false;
      if (obj) { if (lastClick > 0) { if (clickTime < lastClick + timeDiff) {
        eventFired = true;
        lastClick = 0;
        if (obj.audioPlayer.isPlaying) {
          obj.pauseAudio();
        } else {
          obj.playAudio();
        }
      } } };
      if (!eventFired) {
        lastClick = clickTime;
      }
    });
  });
})(jQuery);

The number 500 in the code represents the time difference (500ms) between the two taps. You can change this value if you think the time difference is too long or too short.

If you want to support double-click on regular desktop or laptop computers as well, use the following code:

(function($){
  $(document).ready(function() {
    var timeDiff = 500;
    var lastClick = 0;
    var startEvent = ("ontouchstart" in window) ? "touchstart" : "mousedown";
    $(document).on(startEvent, function() {
      var clickTime = Date.now();
      var obj = $("#wonderpluginaudio-AUDIOPLAYERID").data("object");
      var eventFired = false;
      if (obj) { if (lastClick > 0) { if (clickTime < lastClick + timeDiff) {
        eventFired = true;
        lastClick = 0;
        if (obj.audioPlayer.isPlaying) {
          obj.pauseAudio();
        } else {
          obj.playAudio();
        }
      } } };
      if (!eventFired) {
        lastClick = clickTime;
      }
    });
  });
})(jQuery);