收到错误-未捕获(承诺)的DOMException:play()失败,因为用户未首先与文档进行交互 [英] getting error - Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first
问题描述
我想播放音频作为警报,但是出现诸如未捕获(承诺)的DOMException:play()失败,因为用户没有首先与文档进行交互.
HTML代码:
<audio id="alarm" src="alarm.mp3"></audio>
JavaScript代码:
function alarm() {
var value = document.getElementById("rvoltage").innerHTML;
if (value > 230) {
document.getElementById('alarm').play();
}
}
这是由于许多浏览器不允许HTML元素在页面加载时自动播放音乐和视频以节省带宽等事实,因此您可以创建一个按钮并在点击事件中播放音乐,或设法绕过音乐以使其在页面上的任何点击事件中播放.
在以下情况下,允许自动播放声音: 用户已与域进行了交互(单击,点击等). 在台式机上,已经超过了用户的媒体参与度索引"阈值,这意味着该用户以前曾播放带声音的视频. 在移动设备上,用户已[将该网站添加到了主屏幕].
https://developers.google.com/web /updates/2017/09/autoplay-policy-changes
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.
HTML Code:
<audio id="alarm" src="alarm.mp3"></audio>
JavaScript Code:
function alarm() {
var value = document.getElementById("rvoltage").innerHTML;
if (value > 230) {
document.getElementById('alarm').play();
}
}
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 any click event on your page.
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
这篇关于收到错误-未捕获(承诺)的DOMException:play()失败,因为用户未首先与文档进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!