Detecting HTML5 audio element file not found error

前端 未结 3 1416
暗喜
暗喜 2020-12-30 08:01

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 \"

3条回答
  •  被撕碎了的回忆
    2020-12-30 08:47

    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:

    Non existent audio files - click to play

    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.

提交回复
热议问题