【问题标题】:Detecting HTML5 audio element file not found error检测 HTML5 音频元素文件未找到错误
【发布时间】:2014-06-07 12:36:08
【问题描述】:

如果音频元素 src 属性指向不存在的文件,我试图让浏览器显示警报,但是如果我附加“错误”事件,我不会得到任何响应。

这是我的问题以及我尝试过的问题http://jsfiddle.net/Xx2PW/7/

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>

还有 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!");
});

如何用JS检测文件没有播放(因为找不到)的错误?

【问题讨论】:

    标签: javascript html audio html5-audio


    【解决方案1】:

    当您愿意检测“文件未找到错误”时,您实际上需要绑定到源标签以侦听错误事件。看看这个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>
    

    脚本:

    $("#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!");
        });
    

    在这个MDN article - 部分错误处理中有描述。 让我知道它是否适合你。

    【讨论】:

    • 太棒了,就是这样 - 也感谢文档的链接,一旦你知道它是源元素,它就很有意义。
    • 知道如何在 React 组件中实现这一点吗?
    • 这对我很有用。但是,有没有办法确定导致错误的调用返回的 http 状态码,或者错误是什么?
    • @asubanovsky 您需要在源元素上添加 onError 回调。我的反应技能很生疏,但我在 Vue &lt;source onError={ /* handleErrorFunc */} src="url/soundfile.mp3" /&gt; 中做同样的事情
    【解决方案2】:

    这应该处理这两种情况(例如,使用带有&lt;source&gt; 标签的&lt;audio&gt; 或使用&lt;audio src=""&gt;)。
    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);
        });
    });
    

    【讨论】:

    • 只是指出,使用没有 的音频标签时,handleSourceError 不会触发 ..
    • @rasjani 这就是 handleMediaError 的用途。使用该 sn-p 代码将处理这两种情况。
    • 对于那些可能正在阅读这篇文章但没有意识到两种方法之间有什么区别的人来说,这是一个文字评论。
    • @rasjani 啊,我的错。继续,先生!
    【解决方案3】:

    获取音频错误

    $('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);
    

    引自How to check if HTML5 audio has reached different errors

    【讨论】:

    • 我忘了说 - 我在写问题之前尝试了该解决方案,但它似乎不适用于找不到文件的情况,这不是 MEDIA_ERR_ABORTED、MEDIA_ERR_NETWORK、MEDIA_ERR_DECODE、MEDIA_ERR_SRC_NOT_SUPPORTED。对你起作用吗?我什至无法让我的代码从错误事件处理程序中触发警报,更不用说通过 switch 块运行了。
    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    相关资源
    最近更新 更多