获取“play() 失败,因为用户没有先与文档交互"尝试播放声音时出错(javascript/html) [英] Getting "play() failed because the user didn't interact with the document first" error when trying to play sound (javascript/html)

查看:112
本文介绍了获取“play() 失败,因为用户没有先与文档交互"尝试播放声音时出错(javascript/html)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 javascript 在网页上播放声音,但无论何时,我都会收到上述错误.这是我的代码:

I'm trying to play a sound on a web page using javascript but whenever I do, I get the above error. Here's my code:

if (thing.startsWith("0")) {
    var a = new Audio("audio.mp4");
    a.play();
}

此外,如果您打开控制台,声音会自动开始播放.

Furthermore, if you open the console, the sound automatically starts playing.

推荐答案

由于 Google 更新了自动播放策略,用户需要先与播放声音的窗口进行一些交互,例如例如开始"按钮,然后您可以播放声音.发生这种情况是因为对于许多用户来说,突然播放声音很烦人.

It´s because Google updated its Autoplay Policy, it is necessary for the user to make some interaction first with the window in which the sound will be played, for example a 'Start' button then you can play the sound. This happened because for many users it is annoying when a sound is played out of nowhere.

这篇关于获取“play() 失败,因为用户没有先与文档交互"尝试播放声音时出错(javascript/html)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆