Bootstrap

解决浏览器播放音频声音,没交互前不播放问题

方法一:通过显示“需要播放音频”弹窗,进行交互之后播放。

 <audio ref="audioRef">
   <source src="./mp3/tishi.mp3" />
 </audio>

<script setup>
  import { ref } from 'vue'
  let audioRef = ref(null)
  
  onMounted(() => {
     if (window.performance.navigation.type === 1) {//重新加载
         audioClick()
       } else {
          handelShow()
       }
  })

  const audioClick = () => {
    let startPlayPromise = audioRef.value.play()
    if (startPlayPromise !== undefined) {
      startPlayPromise.catch(error => {
        if (error.name === 'NotAllowedError') {
          // 弹窗引导用户与页面做交互,只需要一个简单的按钮即可
          // 记得在按钮上绑定一个带有play()方法的回调函数,以element-plus的组件为例
          ElMessageBox.alert('当前正在自动播放音频', '提示', {
            confirmButtonText: '确认',
            callback: () => {
              audioRef.value.play()
            },
          })
        }
      })
    }
  }

  const handelShow = () => {
    audioRef.value.play()
  }
</script>

方法二:通过监听页面点击事件,页面有交互之后播放。

 data() {
   return {
         initIntervalPlay:null,
         firstPlayVid: true,
     }
 },

 
mounted() {
  	const audio =document.getElementById("videoSound");
    let startPlayPromise = audio.play();
    if (startPlayPromise !== undefined) {//判断 首次进入用户没交互时,无法播放问题
        startPlayPromise
            .catch((error) => {
                document.removeEventListener('click', this.playHandle)
                document.addEventListener('click', this.playHandle)
            })
            .then(() => {
                this.intervalPlay()
            });
    }
}
  playHandle() {
                if (this.firstPlayVid) {
                    document.getElementById("videoSound").play()
                    this.intervalPlay()
                    this.firstPlayVid = false
                }
            },
            //循环播报提示音
            intervalPlay(){
                if (this.initIntervalPlay) {
                    window.clearInterval(this.initIntervalPlay)
                }
                this.initIntervalPlay = setInterval(() => {
                    document.getElementById("videoSound").play()
                }, 5000)
            }
;