audio的play()报错的解决方法

前两天有个需求,轮询订单,一旦有新订单来了,就要语音播报.当然业务不难,可就是出现的异常是最让人头疼的

当与当前页面没有进行交互时,比如用户刷新了页面后,audio的方法play()调用就会报错,如下图.查找了一些资料后,才知道原来是2018年4月份以后,chrome浏览器对这块进行了优化,为了节约流量,禁止了自动播放,必须由用户交互后才能触发,这就头疼了.

当用户点击网页后,点击任何位置都行,andio就能自动播报了,然后我就想了个方案,设置个按钮,让按钮自动点击,然后触发audio,然而发现这种作弊方案,仍旧不行

后来各种查找方法,想规避,发现标签里加入 muted 也是于事无补,到最后也只有曲线救国方案:

由于play()方法是一个promise,监听它的成功和失败状态,如果失败,那就提醒用户进行交互,设置一个激活按钮,点击后就能触发了,这也是没办法的办法

 1 <template>
 2     <el-button class="autoPlay" type="text" v-if="isShow" @click="autoPlay">激活</el-button>
 3     <!-- audio宽度设0,让其隐藏 -->
 4     <audio muted controls ref="audio" :src="audioSrc" style="width: 0px;"></audio>
 5 </template>
 6 import newOrder from '@/assets/audio/new_order.mp3'
 7 
 8 export default {
 9   data () {
10     return {
11       audioSrc: newOrder,
12       isShow: false
13     }
14   },
15   created() {
16     this.open()
17   },
18   methods: {
19     open() {
20       const myAudio =  document.getElementsByTagName('audio')[0]
21       if (myAudio.canPlayType) {
22         this.autoPlay()
23       } else {
24         this.$message({
25           type: 'error',
26           message: '您的浏览器不支持语音播报'
27         })
28       }
29     },
30     // 自动播放
31     autoPlay() {
32       this.$refs.audio.play().then(() => {
33         this.isShow = false
34       }).catch(() => {
35         this.$message({
36           type: 'error',
37           message: '语音播报失效,点击右上角"激活"按钮'
38         })
39         this.isShow = true
40       })
41     }
42   }
43 }

猜你喜欢

转载自www.cnblogs.com/wx3091/p/12144552.html
今日推荐