1
votes

I have more than 5 audio players with audioplayer.js on a html5 page.

Does anyone has a simple script in js to pause all other players when the current player is playing ?

jQuery:

$( function(){
   $("audio").audioPlayer();
});

Library

https://osvaldas.info/examples/audio-player-responsive-and-touch-friendly/audioplayer.js

I have tried as below

window.player = $('audio')[0];
$('.audioplayer-playpause').click(function () {
    if (player.paused) {
        player.play();
    } else {
        player.pause();
    }
});

I have made a jsFiddle just to easeout things and below is the link:

JS Fiddle for Audio Player

1

1 Answers

6
votes

Try the below code.I have tested it in JS Fiddle & it is working :) :)

Updated JSFiddle

Put this code in Javascript & remove yours.

document.addEventListener('play', function(e){
    // get all <audio> tag elements in the page.
    var allAudios = document.getElementsByTagName('audio');
    // Iterate through all players and pause them, except for
    // the one who fired the "play" event ("target")
    for(var i = 0; i<allAudios.length; i++){
        if(allAudios[i] != e.target){
            allAudios[i].pause();
        }
    }
}, true);