有同学反映有一个奇葩的问题,audio标签 在移动端无法自动播放。尤其是ios系统,在safari以及微信内置浏览器上。
聪明的你肯定能想到如下代码:
var audio = document.getElementById("audioID");
audio.play();
发现不行后思索一番,决定加一个定时器延时执行。一定是audio没加载完的问题,嗯!一定是!我是天才!!!
setTimeout(()=>{
var audio = document.getElementById("audioID");
audio.play();
},1000)
信心满满发上去,发现还是不行。。。。
首先chrome会报如下错误:
Uncaught (in promise) DOMException: play() failed because the user didn’t interact with the document first.
这个与safari不自动播放是一个问题,其实是为了保护用户的流量以及进入网页突然发声体验不友好。
解决办法:
setTimeout(()=>{
var audio = document.getElementById("audioID");
audio.muted = true; // 加一个静音
audio.play();
},1000)
诶,好了!!浏览器都没有问题了哇哈哈哈。然后到了微信发现还是没有好。。。。
微信的解决办法:
// 动态加载微信实例,也可直接引用script标签
if(0 <= navigator.userAgent.toLowerCase().indexOf("micromessenger")
){
const oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = 'https://res2.wx.qq.com/open/js/jweixin-1.6.0.js';
oScript.onload = this.autoplay // 加载成功的回调函数
document.body.appendChild(oScript);
}
autoplay(){
wx.config({ // eslint-disable-line
debug:false,
appId:"",
timestamp:1,
nonceStr:"",
signature:"",
jsApiList:[]
});
wx.ready(function(){ // eslint-disable-line
var audio=document.getElementById("audioID");
audio.play()
})
},
发上去,都好了,哈哈哈,不用加班改bug了~~~