gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:20:45 24 4
gpt4 key购买 nike

如果音频元素的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com