Dondada
Dondada

Reputation: 441

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?

Upvotes: 4

Views: 4321

Answers (3)

S Kumar
S Kumar

Reputation: 258

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

Upvotes: 5

Canaan Etai
Canaan Etai

Reputation: 3785

thats easy with jquery. below is an example of both audio and video

$("audio").on("play", function() {
    var id = $(this).attr('id');

    $("audio").not(this).each(function(index, audio) {
        audio.pause();
    });
});

$("video").on("play", function() {
    var id = $(this).attr('id');

    $("video").not(this).each(function(index, video) {
        video.pause();
    });
});

Upvotes: 0

Nicolai
Nicolai

Reputation: 1953

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();
        }
    });
}

Upvotes: 1

Related Questions