工作手记之ios safari禁止音频自动播放的解决方法

问题场景:

制作一个H5,需要微信打开后背景音乐或者其他音频文件进行播放,但是经常出现的结果是,安卓基本没有问题,但是苹果手机确不行,总是不进行播放,这是为什么呢?

问题原因:

苹果为了用户着想,禁止了Autoplay和JS "onload" 加载播放。

    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.

但是客户却是需要上述效果,那该如何解决呢?

解决方法:

方法一:(依赖touch事件进行播放,但是有时候用户并没有操作,此时就有点尴尬了……)

document.addEventListener('touchstart', function(){ 
    audio.play();
}, false);

方法二:(依赖微信的ready事件进行,但是只能解决微信内部,外部浏览器safari还是不行:(……)

document.addEventListener("WeixinJSBridgeReady", function () {
    audio.play();
}, false);
但是如果作品使用的场景基本基于微信的话,那是用方法二可以基本有效的解决这个问题
同时,当一个H5有多个音频时,可以在ready的callback里面重新load一遍,后面在适当的时机调用play就可以了,不然的话,依然会报出play方法undefined的error。

猜你喜欢

转载自www.cnblogs.com/jlfw/p/12913267.html