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

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

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

1
2
3
<audio id="bg-audio" autoplay="autoplay" loop="loop">
<source src="./love.mp3" />
</audio>

但是查阅资料发现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
<audio id="bg-audio" autoplay="autoplay" loop="loop">
<source src="./love.mp3"/>
</audio>

<script>
// 解决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()
})
</script>

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

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

谢谢小天使请我吃糖果
0%