178

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

Harry
  • 52,711
  • 71
  • 177
  • 261
  • See related: http://stackoverflow.com/questions/6877403/how-to-tell-if-a-video-element-is-currently-playing – mems Dec 02 '16 at 14:13

13 Answers13

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

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

Edric
  • 24,639
  • 13
  • 81
  • 91
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Since there is no stop this is a clean solution. – Todd Moses Feb 25 '12 at 15:03
  • Then `paused` is true and so `isPlaying()` returns false. – Niet the Dark Absol Feb 26 '12 at 14:31
  • 51
    This is wrong answer. I am just working with it, and before the first start .paused is false. – Tomas Jul 30 '12 at 10:49
  • 3
    @Tom you have a jsbin? I tried this and it seems like the correct answer. – Harry Aug 27 '12 at 03:07
  • 4
    @Harry I was playing around with it more and it seems like in some browsers it does work and it some not. I guess it depends on implementation. But for all latest updates for chrome and firefox it seems to work, so This answer is correct for latest implementations. – Tomas Aug 27 '12 at 04:39
  • You can also use the `ended` listener so that you do not restart the audio when it finishes playing. – Dan Feb 01 '19 at 16:59
  • 3
    listen for events! addEventListener('playing', func) and addEventListener('pause', func). – Kristian Oct 12 '19 at 22:50
  • 3
    According to both the [HTML Living Standard](https://html.spec.whatwg.org/multipage/media.html#dom-media-paused) and the [W3C HTML5 spec](https://www.w3.org/TR/html50/embedded-content-0.html#htmlmediaelement), "The `paused` attribute represents whether the media element is paused or not. The attribute must initially be true". Maybe @Harry and @Tomas found this not to be the case in 2012 because the specs were not clear at that point. BUT ... I couldn't find anything in the specs (not to say it's not there!) that says that the 'paused` attribute must be true when playback ends. Any views? – Matt Wallis Nov 06 '19 at 11:19
62

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.

}
JoshJoe
  • 1,482
  • 2
  • 17
  • 35
Maxali
  • 1,934
  • 2
  • 16
  • 25
23

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.

Hassan Mahmud
  • 484
  • 4
  • 13
14
document.getElementsByTagName('audio').addEventListener('playing',function() { myfunction(); },false); 

Should do the trick.

projectxmatt
  • 3,091
  • 2
  • 15
  • 16
  • 2
    `getElementsByTagName('audio')[0]` because it returns collection, not one element – Mik Nov 29 '21 at 22:06
9

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();
     }
}
Alex K
  • 14,893
  • 4
  • 31
  • 32
4

I wondered if this code would work, and it amazingly did:

if (a.paused == false) {
/*do something*/
}

or you could write it as:

if (!a.paused == true) {
/*do something*/
}

if you want your IDE annoying you in JSfiddle.

2

you can to use the onplay event.

var audio = document.querySelector('audio');
audio.onplay = function() { /* do something */};

or

var audio = document.querySelector('audio');
audio.addEventListener('play', function() { /* do something */ };
2

Try Out This Code:

    var myAudio = document.getElementById("audioFile"); 

    function playAudio() { 
          //audio.play(); 
          //console.log(audio.play())
           if (myAudio.paused && myAudio.currentTime >= 0 && !myAudio.started) {
         myAudio.play();
         console.log("started");
     } else {
         myAudio.pause();
     }
}
Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
  • Hello and welcome to SO! While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read the [tour](https://stackoverflow.com/tour), and [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Tomer Shetah Dec 28 '20 at 09:02
1

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.

Alex Ivasyuv
  • 8,585
  • 17
  • 72
  • 90
1

I do this way

    <button id="play">Play Sound</button>
<script>
    var sound = new Audio("path_to_sound.mp3")
    sound.loop = false;
    var play = document.getElementById("play")
    play.addEventListener("click", () => {
        if (!isPlaying()) {
            sound.play()
        } else {
            //sound.pause()  
        }
    })

    function isPlaying() {
        var infoPlaying = false
        var currentTime = sound.currentTime == 0 ? true : false
        var paused = sound.paused ? true : false
        var ended = !sound.ended ? true : false
        var readyState = sound.readyState == 0 ? true : false
        if (currentTime && paused && ended && readyState) {
            infoPlaying = true
        } else if (!currentTime && !paused && ended && !readyState) {
            infoPlaying = true
        }
      return infoPlaying
    }
</script>
AllanRibas
  • 678
  • 5
  • 14
0

I use this for play pause audio button

    var audio=$("audio").get[0];
    if (audio.paused || audio.currentTime == 0 || audio.currentTime==audio.duration){
//audio paused,ended or not started
            audio.play();
        } else {
//audio is playing
            audio.pause();
        }
Toki
  • 268
  • 3
  • 10
-1

am using this jquery code withe tow button play and stop, play button is a play and pouse button

const help_p = new Audio("audio/help.mp3");//Set Help Audio Name
$('#help_play').click(function() {//pause-Play
if (help_p.paused == false) {
  help_p.pause();//pause if playing
} else {
  help_p.play();//Play If Pausing
}
});

$('#help_stop').click(function() {//Stop Button
  help_p.pause();//pause
  help_p.currentTime = 0; //Set Time 0
});
Mohamed Slimane
  • 311
  • 3
  • 14
-3

While there is no method called isPlaying or something similar, there are a few ways to accomplish this.

This method gets the % of progress as audio is playing:

function getPercentProg() {
    var myVideo = document.getElementById('myVideo');
    var endBuf = myVideo.buffered.end(0);
    var soFar = parseInt((endBuf / myVideo.duration) * 100);
    document.getElementById('loadStatus').innerHTML =  soFar + '%';
}

If percent is greater than 0 and less than 100, it is playing, else it is stopped.

Todd Moses
  • 10,969
  • 10
  • 47
  • 65
  • Erm, what if I pause the audio in the middle? – Niet the Dark Absol Feb 25 '12 at 13:31
  • 1
    Then it would not be playing. – Todd Moses Feb 25 '12 at 15:02
  • This only detects the amount buffered. If, for instance, the audio element has begun buffering data but has not started playing because it doesn't have enough data, this method can still return true. Or if the element has buffered data as part of playback and subsequently was paused. – dhasenan Aug 30 '12 at 05:36
  • getElementsByTagName('myVideo') ? i think it should be getElementById('myVideo') – Lucky Soni Feb 01 '13 at 07:31
  • 2
    Em... Why minusing? A great idea, bad written though. How can you check if realtime audio (WebRTC) is playing with .paused? Only with buffer checking. Not deserved minusing. I upvote. – igorpavlov Dec 06 '13 at 10:57
  • Wtf?! Why double-parenthesized parseInt? – m93a Oct 03 '14 at 14:01