audio的踩坑
1、问题描述
使用js播放audio视频时,用户没有点击浏览器,此时是无法触发js事件中的play的,
报错信息如下:Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document
如下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>音节导航</title>
<style>
* {
margin: 0;
padding: 0;
}
body,html{
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
a {
text-decoration: none;
display: block;
width: 100%;
height: 100%;
text-align: center;
}
ul {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
display: flex;
width: 900px;
height: 38px;
line-height: 38px;
list-style: none;
border: 1px solid;
}
ul>li {
display: block;
height: 100%;
flex: 1;
overflow: hidden;
}
ul>li:not(:first-child) {
border-left: 1px solid;
}
ul>li .down {
width: 100%;
height: 100%;
background-color: blue;
transition: 0.5s;
}
ul>li:hover .down {
transform: translateY(-38px);
}
</style>
</head>
<body>
<audio muted></audio>
<ul>
<li>
<a href="javascript:;">导航1</a>
<div class="down"></div>
</li>
<li>
<a href="javascript:;">导航2</a>
<div class="down"></div>
</li>
<li>
<a href="javascript:;">导航3</a>
<div class="down"></div>
</li>
<li>
<a href="javascript:;">导航4</a>
<div class="down"></div>
</li>
<li>
<a href="javascript:;">导航5</a>
<div class="down"></div>
</li>
<li>
<a href="javascript:;">导航1</a>
<div class="down"></div>
</li>
<li>
<a href="javascript:;">导航1</a>
<div class="down"></div>
</li>
<li>
<a href="javascript:;">导航1</a>
<div class="down"></div>
</li>
<li>
<a href="javascript:;">导航1</a>
<div class="down"></div>
</li>
</ul>
</body>
<script>
window.onload = function () {
// console.log(123)
var audio = document.getElementsByTagName("audio")[0]
// audio.muted = false
var lis = document.getElementsByTagName("li")
for (var i=0;i<lis.length;i++) {
lis[i].addEventListener("mouseenter",function() {
audio.src = "../resource/mp3/du.mp3"
audio.muted = false
audio.play()
})
}
}
</script>
</html>
2、原因
目前浏览器策略是,web网页需要至少又一次可信任的用户行为后
解决办法:
可信任的用户行为包括touchstart触摸或者click点击。
使用这两个办法就可以解决这个问题