Detecting HTML5 audio element file not found error

22,814

Solution 1

You actually need to bind to the source tag for listening to error event when willing to detect "file not found error". Have a look at this fiddle.

HTML:

<p id="player1">Non existent audio files - click to play</p>

<audio preload="none" controls>
    <source id="wav" src="http://example.com/non-existant.wav" />
    <source id="mp3" src="http://example.com/non-existant.mp3" />
    <source id="ogg" src="http://example.com/non-existant.ogg" />
</audio>

Script:

$("#player1").on("click", function () {
    //I've tried catching the error like this - no effect
    alert("Trying to play file.");
    try {
        $('audio')[0].play();
    } catch (e) {
        alert("Error playing file!");
    }
});

$("audio").on("error", function (e) {
        alert("Error at audio tag level!");
    });

// try this then
$("#wav").on("error", function (e) {
        alert("Error with wav file!");
    });
$("#mp3").on("error", function (e) {
        alert("Error with mp3 file!");
    });
$("#ogg").on("error", function (e) {
        alert("Error with ogg file!");
    });

It is described in this MDN article - section error handling. Let me know if it works for you.

Solution 2

This should handle both cases (e.g. using <audio> with <source> tags or using <audio src="">).
See example fiddle.

function handleSourceError(e) { alert('Error loading: '+e.target.src) }
function handleMediaError(e) {
    switch (e.target.error.code) {
        case e.target.error.MEDIA_ERR_ABORTED:
            alert('You aborted the media playback.'); break;
        case e.target.error.MEDIA_ERR_NETWORK:
            alert('A network error caused the media download to fail.'); break;
        case e.target.error.MEDIA_ERR_DECODE:
            alert('The media playback was aborted due to a corruption problem or because the media used features your browser did not support.'); break;
        case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
            alert('The media could not be loaded, either because the server or network failed or because the format is not supported.'); break;
        default:
            alert('An unknown media error occurred.');
    }
}

var toArray = Array.prototype.slice;
toArray.apply(document.getElementsByTagName('audio')).forEach(function(audio){
    audio.addEventListener('error', handleMediaError);
    toArray.apply(audio.getElementsByTagName('source')).forEach(function(source){
        source.addEventListener('error', handleSourceError);
    });
});

Solution 3

Getting audio errors

$('audio').addEventListener('error', function failed(e) {
   // audio playback failed - show a message saying why
   // to get the source of the audio element use $(this).src
   switch (e.target.error.code) {
     case e.target.error.MEDIA_ERR_ABORTED:
       alert('You aborted the video playback.');
       break;
     case e.target.error.MEDIA_ERR_NETWORK:
       alert('A network error caused the audio download to fail.');
       break;
     case e.target.error.MEDIA_ERR_DECODE:
       alert('The audio playback was aborted due to a corruption problem or because the video used features your browser did not support.');
       break;
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
       alert('The video audio not be loaded, either because the server or network failed or because the format is not supported.');
       break;
     default:
       alert('An unknown error occurred.');
       break;
   }
 }, true);

Quoted from How to check if HTML5 audio has reached different errors

Share:
22,814
WojtekD
Author by

WojtekD

Updated on July 09, 2022

Comments

  • WojtekD
    WojtekD almost 2 years

    I am trying to make a the browser display an alert if an audio element src attribute points to a non existent file, however I do not get any response if I attach the the "error" event.

    Here's a fiddle with my problem and with what I have tried http://jsfiddle.net/Xx2PW/7/

    The HTML:

    <p>Non existent audio files - should return an error
        <audio preload="auto">
            <source src="http://example.com/non-existant.wav" />
            <source src="http://example.com/non-existant.mp3" />
            <source src="http://example.com/non-existant.ogg" />
        </audio>
    </p>
    <p>Existing audio file - should just play
        <audio preload="auto">
            <source src="http://jplayer.org/audio/m4a/Miaow-07-Bubble.m4a" />
        </audio>
    </p>
    

    And the JS:

    playerMarkup = "<a class=\"player\">Play</a>";
    audioTags = $("audio");
    
    audioTags.before(playerMarkup); //insert markup before each audio tag
    
    $(".player").on("click", function () {
        currentAudio = $(this).next()[0];
        //I've tried catching the error like this - no effect
        alert("Trying to play file.");
        try {
            currentAudio.play();
        } catch (e) {
            alert("Error playing file!");
        }
    });
    
    //I've also tried just handling the event error - no effect
    audioTags.on("error", function (e) {
        alert("Error playing file!");
        console.log("Error playing file!");
    });
    

    How can I detect an error of the file not being played (because of not being found) with JS?

  • WojtekD
    WojtekD about 10 years
    I forgot to say - I tried that solution before writing the question, and it does not seem to work for the scenario of file not found, which is none of MEDIA_ERR_ABORTED, MEDIA_ERR_NETWORK, MEDIA_ERR_DECODE, MEDIA_ERR_SRC_NOT_SUPPORTED. Does it work for you? I cannot get my code to even fire the alert from the error event handler, not to mention running through a switch block.
  • WojtekD
    WojtekD about 10 years
    Brilliant, that's it - thanks for the link to the documentation as well, once you know it's the source element, it makes a lot of sense.
  • rasjani
    rasjani about 9 years
    Just to point out, handleSourceError does not trigger when using audio tag without <source> ..
  • idbehold
    idbehold about 9 years
    @rasjani that's what the handleMediaError is for. Using that snippet of code will handle both cases.
  • rasjani
    rasjani about 9 years
    it was a literal comment for people who might be reading this and not realizing what is the difference between two approaches.
  • idbehold
    idbehold about 9 years
    @rasjani ahh, my mistake. Carry on, sir!
  • asubanovsky
    asubanovsky over 7 years
    Any idea how to this in React component?
  • Bauer
    Bauer about 7 years
    This worked great for me. However, is there a way to determine either the http status code returned from the call that caused the error, or what the error was?
  • Rankinstein
    Rankinstein over 3 years
    @asubanovsky you'd need to add an onError callback on the source element. My react skills are rusty but I'm doing the equivalent in Vue <source onError={ /* handleErrorFunc */} src="url/soundfile.mp3" />