在2018年4月份發布的Chrome 66正式關掉了聲音自動播放,也就是說<audio autopaly></audio>
<video autoplay></video>
在桌面版瀏覽器也失效。
頁面在用戶沒有操作的情況下播放聲音會出現報錯:
圖片示例:
代碼示例:
<!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>Document</title>
</head>
<body>
<audio id="testAudio" src="./chat.mp3"></audio>
<script>
document.querySelector('#testAudio').play();
</script>
</body>
</html>
解決方案1(把瀏覽器聲音設置為允許):


解決方案2(判斷到瀏覽器不能自動播放,給一個彈框讓用戶點擊后再播放):
圖片示例:
代碼示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
<el-dialog :visible.sync="visible" title="提示" :before-close="handleClose">
<p>是否播放提示音?</p>
<span slot="footer" class="dialog-footer">
<el-button @click="handleClose">取 消</el-button>
<el-button type="primary" @click="handleClose">確 定</el-button>
</span>
</el-dialog>
</div>
</body>
<audio id="chat" src="./chat.mp3"></audio>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: '#app',
data: function () {
return {
visible: false
}
},
created() {
this.playPay();
},
methods: {
playPay() {
const audioPlay = document.querySelector('#chat').play();
audioPlay.then(() => {
console.log('可以自動播放');
}).catch((err) => {
console.log('不允許自動播放');
this.visible = true;
});
},
handleClose() {
this.visible = false;
//音頻元素只在用戶交互后調用.play(),
document.querySelector('#chat').play();
}
},
})
</script>
</html>
我暫時找到這兩個解決方案,如果大家有更好的方案可以提出來。