原因:
Chrome等浏览器基于安全的策略,于早几年就已经停止自动播放
解决方法:
进入页面随便点击一下页面,这样用户和浏览器就产生了交互,可以开启自动播放
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>解决背景音乐无法播放问题</title>
</head>
<body>
<audio src="http://www.w3school.com.cn/i/song.mp3" id="music" autoplay preload controls></audio>
<script type="text/javascript">
function toggleSound() {
var music = document.getElementById("music");//获取ID
console.log(music);
console.log(music.paused);
if (music.paused) { //判读是否播放
music.paused=false;
music.play(); //没有就播放
}
}
setInterval("toggleSound()",1);
</script>
</body>
</html>