Skip to content Skip to sidebar Skip to footer

Multiple Audio Html : Auto Stop Other When Current Is Playing With Javascript

I have 10 audio players with simple html audio tags on a html5 page. No jquery, no special audio js plugins, etc... Does anyone has a simple script in js to pause all other players

Solution 1:

you can use event delegation. Simply listen to the play event in the capturing phase and then pause all video file, but not the target one:

document.addEventListener('play', function(e){
    var audios = document.getElementsByTagName('audio');
    for(var i = 0, len = audios.length; i < len;i++){
        if(audios[i] != e.target){
            audios[i].pause();
        }
    }
}, true);

Solution 2:

Instead of looping over all audio tags on a page and pausing them, you can store a reference to the currently playing element, and have only that one pause when playing another.

document.addEventListener("play", function(evt) {
    if(this.$AudioPlaying && this.$AudioPlaying !== evt.target) {
        this.$AudioPlaying.pause();
    }
    this.$AudioPlaying = evt.target;
}, true);

Solution 3:

Mixing both previous answers that didn't work, i've used that. I just added && window.$_currentlyPlaying != evt.target and all is working. Also i've created a gist with this and other goodies for audio tags. javascript-audio-tags

window.addEventListener("play", function(evt)
{
    if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
    {
        window.$_currentlyPlaying.pause();
    } 
    window.$_currentlyPlaying = evt.target;
}, true);

Solution 4:

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

Solution 5:

I don't know if it is because of Chrome updates, but the previous answers did not work for me. I modified a bit of the code here and came up with this:

document.addEventListener("play", function(evt)
{
    if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
    {
        window.$_currentlyPlaying.pause();
    } 
    window.$_currentlyPlaying = evt.target;
}, true);

I don't know why, but the widow.addEventListener was not working for me, but I liked the idea of having the currentPlaying variable stored in the window element instead of having to create it outside of the listener prior to using it.

Post a Comment for "Multiple Audio Html : Auto Stop Other When Current Is Playing With Javascript"