若是咱们想要在一个页面自动播放背景音乐或是其余音频,好比ios是没办法调用audio.play()事件直接调用,非得添加手动点击事件才能够。接下来就说说我在项目里遇到的困难和解决办法.
状况一、咱们知道安卓是能够直接调用音频的play事件的,ios不行。如是在单独的h5页面,无路由,这种状况就必须加个引导按钮点击它,或是在页面全局设置一个点击事件one,当用户第一次且仅第一次碰到页面就播放。这里用vue距举例:vue
<template> <view v-on:touchstart.once="playBgMusic()"></view> </template> methods: { playBgMusic () { let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); if (isiOS) this.bgMusic.play(); } } mounted(){ this.bgMusic = new Audio(); this.bgMusic.loop = true; this.bgMusic.src = require('xxx.mp3'); this.bgMusic.load(); this.bgMusic.play(); }
状况二、若是是当用户使用hash或者有路由跳转的状况,能够使用在跳转页添加全局audio对象的方式来控制。这里使用vue举例:首先可在router/index.js里设置window.audio=null,在跳转前的页面new一个video 并将此对象赋予window.audio,而后便可在下一个页面使用audio对象。代码:ios
/*router/index.js*/ window.bgMusic=null; /*跳转页面 router/beforeGo.js 跳转事件*/ <view @click="goTo()">跳转到自动播放音乐的页面</view> methods: { goTo () { const audio = new Audio(); audio.addEventListener('canplay', () => {audio.play()}); audio.loop = true; audio.src = mathBgVoice; audio.load(); bgMusic = audio; this.$router.replace('自动播放音乐的页面路由') } }
状况3:若是你的业务主要是在微信上,那么能够使用如下代码,可实如今微信浏览器中iOS和安卓设备中自动播放音频的效果:浏览器
var play = function() { document.removeEventListener("WeixinJSBridgeReady", play); document.removeEventListener("YixinJSBridgeReady", play); audioCtx.play(); }; document.addEventListener("WeixinJSBridgeReady",play, false); document.addEventListener('YixinJSBridgeReady', play, false);
这样处理之后,在跳转页面先寻找播放时机,等跳转到播放音乐的页面便可实现‘自动播放背景音乐’的功能。微信