vue背景音频播放以及failed because the user didn‘t interact with the document first问题

先说一下报错的原因
在用户没有任何操作的情况下直接播放背景音乐是不行的,有的浏览器支持有的不支持。错误的意思是,在尝试访问用户的文件系统或数据库之前,用户未与文档进行任何交互。

背景音频的使用

第一种

javascript 复制代码
<audio id="background-music" style="visibility: visible;" src="xxxxxx.mp3"></audio>

mounted() {
  //当鼠标点击后就有了交互事件,再获取音频播放
   document.addEventListener('click', (event) =>{
    	console.log('开始音频')
   		const audio = document.getElementById('background-music');
  		audio.play();
   })
    //   document.addEventListener('keydown', function(event) {
    //     console.log('按下键盘键码:');
    //   });
},

第二种

javascript 复制代码
mounted() {
  //当鼠标点击后就有了交互事件,再获取音频播放
   document.addEventListener('click', (event) =>{
	 let audio = new Audio();
	 audio.controls = false; //这样控件才能显示出来
	 audio.src = 'xxxxx.mp3'; //音乐的路径
	 document.body.appendChild(audio);
	 audio.play();
 })
}
相关推荐
無名路人1 小时前
小程序点餐页吸顶滚动之分类按需加载,上划切换
前端·vue.js·微信小程序
OpsEye3 小时前
当企业不再只关心能不能调用模型,而是关心值不值得调用
javascript·ai编程
FYKJ_20103 小时前
springboot雅集社区养老管理系统04456-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
FYKJ_20103 小时前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
javascript·vue.js·spring boot·mysql·typescript·spark·express
FYKJ_20104 小时前
springboot羽毛球场地管理系统00626-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
晓得迷路了4 小时前
栗子前端技术周刊第 148 期 - Turborepo 2.11、Chrome 154 iframe、Node.js 26...
前端·javascript·css
FYKJ_20104 小时前
django药饮个性化推荐系统54839-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
默_笙10 小时前
🚓 分诊台与拆题术:让 RAG 学会判断和规划
前端·javascript
呃呃呃呃ex10 小时前
10. 现代前端工程化:ES6 React 项目实战与原理解析
前端·javascript
浪遏10 小时前
D2C 系统架构复盘:从设计稿到代码,我们踩过的坑和最终方案
前端·javascript·后端