Search code examples
javascriptjqueryhtmlhtml5-audio

How to detect with jQuery or JavaScript when HTML5 <audio> element cannot play


I have a number of audio elements on a page with mp3s from a remote site and sometimes the request to load an mp3 results in a 301 Moved Permanently response.

When this happens, the player becomes greyed-out but I am unable to detect any error. I tried doing something like this, but the handler is never run:

$('audio').on('error', function(){
    // Code to handle the error 
});

I've noticed that the audio element's networkState is 3 and it's readyState is 0 when I check these in the console after the page has finished loading, but I can't find an event to handle that occurs after these states are reached.

How can I do something (run a function, display a modal, etc) when an mp3 fails to load and the audio element becomes unplayable?


Solution

  • Here is a simple solution!

    window.onload=function(){
      let audioElem=document.querySelectorAll("audio")[0];
      canBePlayed(audioElem);
    }
    function canBePlayed(audio){
     if(audio.readyState!=0){
      alert("This audio can be played!");
     }else{
      alert("This audio can not be played!");
     }
    }
    <audio src="./audio.ogg" controls>
      Your Browser doesn't support this type of audios
    </audio>