<audio id="audio" loop controls src="yellow.mp3">
(该浏览器不支持音频播放组件)
</audio>
<script>
const ele = document.querySelector("#audio");
let isAudioLoaded = false;
let isUserActioned = false;
function Play(e) {
console.log(e.type);
if (e.type === "click") isUserActioned = true;
else isAudioLoaded = true;
if (!isAudioLoaded) return console.log("音频未就绪");
if (!isUserActioned) return console.log("等待用户事件");
ele.load();
ele.play();
ele.oncanplay = undefined;
}
ele.oncanplay = Play;
window.addEventListener("click", Play, { once: true });
</script>
h5 标签 audio 不允许在没有用户操作时进行自动自动播放。否则会报一个 DOMException: play() failed because the user didn't interact with the document first.
的错误。
-
不管用:改为静音模式(muted 属性)
-
不管用:使用 js 模拟一个用户操作(调试工具也是页面的一部分,所以会出现在调试工具中 play 方法可成功)
必须由用户操作一个页面(随便点下哪里)才行。
如果在音频未加载完成就调用 play 用报Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().
或者Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.
。需要 oncanplay 之后再播放。
网友评论