Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop other audio elements from playing with jQuery

I have multiple default HTML5 audio players on a single HTML page. I'm trying to make it so when you play one file and then play the other. The first file will pause.

I started and created a function as follows:

allAudioEls = $('audio');

    function pauseAllAudio() {
       allAudioEls.each(function() {
          var a = $(this).get(0);
          a.pause();
       });
    }

whats the next step?

like image 454
Dondada Avatar asked Sep 19 '25 00:09

Dondada


2 Answers

I Think this is the best Answer for you : Stop other Audio ...

You need to add the following Script only with JQuery.

JavaScript:

$("audio").bind("play",function (){
  $("audio").not(this).each(function (index, audio) {
    audio.pause();
  });
});
//Must be added at the bottom in HTML CODE
like image 123
S Kumar Avatar answered Sep 20 '25 15:09

S Kumar


I think this is what you're looking for: JsFiddle link

Html:

<audio id="audio" controls>
</audio>
<audio id="audio1" controls>    
</audio>

Javascript:

$("audio").each(function(){
  $(this).bind("play",stopAll);
});

function stopAll(e){
    var currentElementId=$(e.currentTarget).attr("id");
    $("audio").each(function(){
        var $this=$(this);
        var elementId=$this.attr("id");
        if(elementId!=currentElementId){
            $this[0].pause();
        }
    });
}
like image 34
Nicolai Avatar answered Sep 20 '25 15:09

Nicolai