javascript - 检测 HTML5 音频元素文件未找到错误

标签 javascript html audio html5-audio

如果音频元素的 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 检测文件未播放(因为未找到)的错误?

最佳答案

当愿意检测“文件未找到错误”时,您实际上需要绑定(bind)到源标记以监听错误事件。看看这个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 中有描述- 部分错误处理。 让我知道它是否适合您。

关于javascript - 检测 HTML5 音频元素文件未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23231404/

相关文章:

javascript - 如何使用 javascript 和 html 防止表格中的第一行

javascript - Chrome:避免在SPA中使用自动填充密码

html - CSS 问题

android - 关于 ALSA 驱动 : How to handle Audio Devices correctly

ios - iPhone同时声音输出

javascript - 在链接按钮 Telerik 上从服务器端调用 javascript

javascript - 如何使用 JS 将 html 元素放置在某个绝对坐标中,而不管主体样式(位置、边距)如何?

python - 是否有一个python库,可让我组合在一起并从自定义波形列表中导出mp3文件?

javascript - 使用 CoffeeScript 为选择框选择默认值

javascript - 关于 Menu Child's Slide Toggle jQuery