关于移动端audio不能自动播放

做h5时有个需求,要求音乐自动播放和切换,后来发现移动端浏览器对Audio的autoplay做了诸多限制,纠结万分,经过多次测试和文档查找,这里整理一下。

IOS

苹果“为了用户着想”,禁止了相关preload和autoplay行为,需要用户主动触发。onload、onready、setTimeout下同样失效。(ios4.2.1以前还是可以的,苹果真是矫情)

苹果官方开发文档有相关说明:

User Control of Downloads Over Cellular Networks

In Safari on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and autoplay are disabled. No data is loaded until the user initiates it. This means the JavaScript play() and load() methods are also inactive until the user initiates playback, unless the play() or load() method is triggered by user action. In other words, a user-initiated Play button works, but an onLoad=”play()” event does not.

经过测试,还是有部分ios手机能够自动播放嘀。(偏偏我的手机就是不行)

不能播放时的解决方案: 让用户“主动”来播放音乐,例如在touchstart事件调用Audio.play。

1
document.addEventListener('touchstart', ()=> audio.play(), false);

Android

安卓下本来是没有什么问题的,结果又学苹果这一套,在安卓5.x之后加了限制,如果不能播放,解决方法同上。

微信

微信不知道加了什么黑科技,大部分情况下(包括IOS和Android)都能自动播放,再不行,可以试试以下的方案:

1
document.addEventListener("WeixinJSBridgeReady", ()=> audio.play(), false);

1
wx.ready(()=> audio.play());

前端就是折腾~