window.onload = function() {
document.getElementById("up").play();
alert("k");
}<audio id="up" src="./res/up.mp3" loop="loop"></audio>
嗨,我刚开始学习html&js,上面的代码在IE上运行得很好,但是只有警告发生在chrome上。这是正常的吗?
发布于 2018-06-29 18:08:28
这是因为chrome抛出了一个异常:
DOMException:元素没有支持的源。
"code": 9,
"name": "NotSupportedError",
"message": "The element has no supported sources."Chrome改变了它的政策,因为blocking roughly half of unwanted media autoplays
读:https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
参考资料:
自动播放策略推出在M66稳定的音频和视频元素,并有效地阻止了大约一半不想要的媒体自动播放在Chrome。对于,自动播放策略将在M70中启动。这会影响到使用音频功能的web游戏、一些WebRTC应用程序和其他网页。开发人员需要更新他们的代码以利用策略。更多详细信息可以在下面的部分中找到。
Chrome's autoplay policies are simple:
我已经编辑了您的代码以显示错误。
window.onload = function() {
const playPromise = document.getElementById("up").play();
// In browsers that don’t yet support this functionality,
// playPromise won’t be defined.
if (playPromise !== undefined) {
playPromise.then(function() {
// Automatic playback started!
}).catch(function(error) {
console.log(error);
// Automatic playback failed.
// Show a UI element to let the user manually start playback.
});
}
alert("k");
}<audio id="up" src="http://hcmaslov.d-real.sci-nnov.ru/public/mp3/Queen/Queen%20'Back%20Chat'.mp3" loop="loop"></audio>
发布于 2018-06-29 18:07:54
这是Chrome的自动播放策略的结果,它限制站点在用户与页面交互之前播放音频。
发布于 2018-06-29 18:26:31
总之,自2018年4月以来,Chrome中的autoplay是默认禁止的。这是为了保护用户不想听到的声音。更多信息。
但是,如果用户与页面交互(例如通过单击),那么是允许的,因此您可以将onload代码更改为单击。如下所示:
window.addEventListener("click", function(event) {
document.getElementById("up").play();
alert("k");
});点击页面和walla。
希望能帮上忙。
https://stackoverflow.com/questions/51106932
复制相似问题