0
votes

I want to play only one audio at a time in response to some mouse event. The situation is onmouse over event on different HTML element plays audio. It becomes noisy when a user moves the mouse fast from one element to another and both the element plays audio. I want to check whether any audio is being played before playing a new audio. I used following code:

var $audioAnno=0;
function audioAnnotation(y){
    var audio; 
    if ($audioAnno==0){
        $audioAnno=1;
        audio = new Audio(y);
        audio.play();
        $audioAnno=0;
    }
}

It does not stop the 2nd audio to play.

2

2 Answers

0
votes

this is how, I would do it, maintain a flag canPlay and on mouse event, if true, then play

canPlay = true;
var es = document.getElementsByTagName('audio'), audios=[];
for(var i=0;i<es.length;i++)    audios.push(es[i]);
audios.forEach(function(e){
    e.addEventListener('play', function(){
        canPlay= false;
    });

    e.addEventListener('ended', function(){
        canPlay= true;
    });
});

// later on some mouseEvent based on some condition

function onMouseEvent(audioElement){
    if(canPlay){
        audioElement.play();
    }
};

Edit: fiddle demo.

Edit2:

same thing with just audio object:

 var audio = new Audio(), canPlay = true;
audio.src = 'http://upload.wikimedia.org/wikipedia/en/f/f9/Beatles_eleanor_rigby.ogg';
audio.addEventListener('play', function(){
    console.log('playing');
    canPlay = false;
});
audio.addEventListener('ended', function(){
    console.log('stopped');
    canPlay = true;
});
audio.play();


//similar mouse event listener changes to 
function onMouseEvent(){
    if(canPlay){
        //audio.src ='...'; // providing new source
        audio.play();
    }
};
0
votes

Thanks all.

I could solve the problem. I used following code:

var $audioAnno=0;
function audioAnnotation(x, y){
    var audio = new Audio(y);
    if ($audioAnno==0){
        $audioAnno = 1;
        audio.play();
        audio.addEventListener("ended", function(){ $audioAnno = 0; });
    }
}