html audio ios自动播放,解决ios下音频(audio)无法自动播放(autoplay)的问题

6824a61d375e8f41bd1bfda2f8289fd3.png

这个博客的虐狗页面一直是设置了自动播放背景音乐,之前测试的时候发现iphone和ipad pro都无法自动播放。当时也没太注意,今天再想起这个问题的时候强迫症犯了,觉得别人要是听不到歌会不会觉得逼格不够。于是还是寻求了一下解决办法。

P.S. 虐狗页面已下架,关注代码即可。

之前是直接在html里写了一句:

1

2

3

但是查阅资料发现ios以安全为名禁用了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.

所以就只能在 document 绑定 touchstart/click 事件,用户触摸或者点击屏幕,音频就自动播放。

修改后的代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

// 解决iOS禁止自动播放音频

// 微信自动播放音频

let bgAudio = document.getElementById('bg-audio');

bgAudio.play();

document.addEventListener("WeixinJSBridgeReady", function () {

bgAudio.play();

}, false);

// 其他应用在click/touch时触发播放

document.addEventListener('click', function () {

bgAudio.play()

})

document.addEventListener('touchstart', function () {

bgAudio.play()

})

现在我正听着虐狗页的背景音乐满意地准备午睡了~

不信你用你的iphone点这里就知道啦~\(≧▽≦)/~啦啦啦


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部