谷歌浏览器不能播放audio 报错Uncaught (in promise) DOMException

在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>

 

 我暂时找到这两个解决方案,如果大家有更好的方案可以提出来。

 

posted @ 2019-12-25 16:52  飞宇1016  阅读(1706)  评论(0编辑  收藏  举报