HTML5 check if audio is playing?

HTML5 check if audio is playing?

What’s the javascript api for checking if an html5 audio element is currently playing?

Solutions/Answers:

Solution 1:

function isPlaying(audelem) { return !audelem.paused; }

The Audio tag has a paused property. If it is not paused, then it’s playing.

Solution 2:

You can check the duration. It is playing if the duration is more than 0 seconds and it is not paused.

var myAudio = document.getElementById('myAudioID');

if (myAudio.duration > 0 && !myAudio.paused) {

    //Its playing...do your job

} else {

    //Not playing...maybe paused, stopped or never played.

}

Solution 3:

document.getElementsByTagName('audio').addEventListener('playing',function() { myfunction(); },false); 

Should do the trick.

Solution 4:

While I am really late to this thread, I use this implementation to figure out if the sound is playing:

service.currentAudio = new Audio();

var isPlaying = function () {
    return service.currentAudio
        && service.currentAudio.currentTime > 0
        && !service.currentAudio.paused
        && !service.currentAudio.ended
        && service.currentAudio.readyState > 2;
}

I think most of the flags on the audio element are obvious apart from the ready state which you can read about here: MDN HTMLMediaElement.readyState.

Solution 5:

Try this function!
Audio playing would not be executed if the position is the beginning or ending

function togglePause() {
     if (myAudio.paused && myAudio.currentTime > 0 && !myAudio.ended) {
         myAudio.play();
     } else {
         myAudio.pause();
     }
}

Solution 6:

To check if audio is really start playing, especially if you have a stream, need to check audio.played.length to 1. It will be 1 only if audio is really start sounds. Otherwise will be 0. It’s more like a hack, but that still works even in mobile browsers, like Safari and Chrome.