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

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

javascript 复制代码
 <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>

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

javascript 复制代码
 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)
            }
相关推荐
方见华Richard20 分钟前
世毫九量子原住民教育理念全书
人工智能·经验分享·交互·原型模式·空间计算
iWZXQxBO38 分钟前
运动控制卡 倒R角程序 G代码 halcon联合运动控制卡联合相机 运动控制卡内容
音视频
铅笔侠_小龙虾1 小时前
Flutter 实战: 计算器
开发语言·javascript·flutter
大模型玩家七七1 小时前
梯度累积真的省显存吗?它换走的是什么成本
java·javascript·数据库·人工智能·深度学习
2501_944711431 小时前
JS 对象遍历全解析
开发语言·前端·javascript
发现一只大呆瓜2 小时前
虚拟列表:支持“向上加载”的历史消息(Vue 3 & React 双版本)
前端·javascript·面试
微祎_2 小时前
Flutter for OpenHarmony:构建一个 Flutter 重力弹球游戏,2D 物理引擎、手势交互与关卡设计的工程实现
flutter·游戏·交互
阔皮大师2 小时前
INote轻量文本编辑器
java·javascript·python·c#
lbb 小魔仙2 小时前
【HarmonyOS实战】React Native 表单实战:自定义 useReactHookForm 高性能验证
javascript·react native·react.js
_codemonster2 小时前
Vue的三种使用方式对比
前端·javascript·vue.js