javascript 获取错误 - 未捕获(承诺)DOMException:play() 失败,因为用户没有先与文档交互
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52963608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting error - Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first
提问by Krishna Mohan
I want to play audio as an alert but I'm getting an error like "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
我想播放音频作为警报,但我收到一个错误,如“未捕获(承诺)DOMException:播放()失败,因为用户没有先与文档交互。
HTML Code:
HTML代码:
<audio id="alarm" src="alarm.mp3"></audio>
JavaScript Code:
JavaScript 代码:
function alarm() {
var value = document.getElementById("rvoltage").innerHTML;
if (value > 230) {
document.getElementById('alarm').play();
}
}
回答by Devilscomrade
That is due to the fact that many browsers do not allow HTML elements to autoplay music and videos on page-load to save bandwidth etc. You could create a button and play the music on a click event or hack your way around it to make it play on anyclick event on your page.
这是因为许多浏览器不允许 HTML 元素在页面加载时自动播放音乐和视频以节省带宽等。您可以创建一个按钮并在点击事件上播放音乐或绕过它来制作它播放页面上的任何点击事件。
Autoplay with sound is allowed if: User has interacted with the domain (click, tap, etc.). On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound. On mobile, the user has [added the site to their home screen].
在以下情况下允许自动播放声音: 用户已与域交互(单击、点击等)。在桌面上,用户的媒体参与指数阈值已被超过,这意味着用户之前曾播放过有声视频。在移动设备上,用户已[将该站点添加到他们的主屏幕]。
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
回答by Sami Ahmed Siddiqui
Just add the mutedattribute in your HTML:
只需muted在 HTML 中添加属性:
<audio id="alarm" src="alarm.mp3" muted></audio>
In JS, just unmute the audio once it gets played.
在 JS 中,只需在播放后取消静音即可。
function alarm() {
var value = document.getElementById("rvoltage").innerHTML;
if (value > 230) {
document.getElementById('alarm').play();
document.getElementById('alarm').muted = false;
}
}
I didn't tested this code but i think, it should work well according to the new policy.
我没有测试这段代码,但我认为,根据新政策,它应该可以很好地工作。
You can get the details of the autoplay policy from here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
您可以从此处获取自动播放政策的详细信息:https: //developers.google.com/web/updates/2017/09/autoplay-policy-changes

