The audio play () method to resolve the error

Two days ago there is a demand, polling order, once the new orders come, we must voice broadcast. Of course business is not difficult, but just appear abnormal is the most vexing

After when there is no interaction with the current page, such as the user refreshes the page, audio method play () call will throw an error, as shown below. Finding some information, I realized that after April 2018, chrome browser this has been optimized in order to save traffic, banned auto-play, can be triggered by user interaction, which is a headache.

When the user clicks on the page, click anywhere will do, andio will automatically broadcast, and then I thought of a scheme, set up a button so auto-click, and then trigger audio, however, found that the cheating scheme, still does not work

Later find a variety of methods, to avoid, found tag added  muted  does not help, in the end, only Quxianjiuguo program:

Since the play () method is a promise, monitor its success and failure status, if that fails, then alert the user to interact, set up an activation button, when clicked, will be able to trigger, and this is no way to approach

 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      the this .Open ()
 . 17    },
 18 is    Methods: {
 . 19      Open () {
 20 is        const = myAudio document.getElementsByTagName ( 'Audio') [0 ]
 21 is        IF (myAudio.canPlayType) {
 22 is          the this .autoPlay ( )
 23        } the else {
 24-          the this $ the Message ({.
 25            of the type: 'error' ,
 26            the Message: 'your browser does not support voice broadcast'
 27          })
 28        }
 29      }
 30      // autoplay 
31     the autoPlay () {
 32        the this .. $ refs.audio.play () the then (() => {
 33 is          the this .isShow = to false 
34 is        .}) the catch (() => {
 35          the this . Message $ ({
 36            type: 'error' ,
 37 [            Message: 'voice broadcast failure, top right corner of the "activate" button'
 38 is          })
 39          the this .isShow = to true 
40        })
 41 is      }
 42 is    }
 43 is }

Guess you like

Origin www.cnblogs.com/wx3091/p/12144552.html