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

 <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)
            }
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐