Play one HTML audio element at a time

倾然丶 夕夏残阳落幕 提交于 2019-12-04 05:10:42
$(function(){
    $("audio").on("play", function() {
        $("audio").not(this).each(function(index, audio) {
            audio.pause();
        });
    });
});

See sample at JSFiddle

Nathan Long

Vanilla JS solution

Here's a solution that doesn't require jQuery.

function onlyPlayOneIn(container) {
  container.addEventListener("play", function(event) {
  audio_elements = container.getElementsByTagName("audio")
    for(i=0; i < audio_elements.length; i++) {
      audio_element = audio_elements[i];
      if (audio_element !== event.target) {
        audio_element.pause();
      }
    }
  }, true);
}

document.addEventListener("DOMContentLoaded", function() {
  onlyPlayOneIn(document.body);
});

Some things to note:

Assuming that your syntax for stopping and pausing tracks is correct (I don't know anything about the audio element), you should be able to do something like this:

$(".playback").click(function(e) {

  // pause all other tracks
  $('.audio').each(function () {
    var song = this;
    if (!song.paused) { song.pause(); }
  });

  // play the audio associated with this element
  this.play();

});

Little Modification to LostInComputer's Answer

In Your HTML Write:

<audio controls onplay="pauseOthers(this);" >
                    <source src="SourcePath">

                </audio>

In Js Write:

function pauseOthers(ele) {
                $("audio").not(ele).each(function (index, audio) {
                    audio.pause();
                });
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!