Html-Safari自动播放音乐

iOS系统的内置浏览器Safari禁止视频和音频的自动播放。

参考:

1
2
3
4
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.
This plays the movie: <input type="button" value="Play" onclick="document.myMovie.play()">
This does nothing on iOS: <body onload="document.myMovie.play()">

所以,需要在页面加载的时候,模拟一个用户触碰的响应动作,来播放音乐,并在音乐开始播放后,移除该响应动作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<audio id = "audio" autoplay loop>
<source src="情歌悠扬.mp3" type="audio/mp3" />
</audio>
<script>
function forceSafariPlayAudio() {
audio.load();
audio.play();
}
var audio = document.getElementById('audio');
audio.addEventListener('play', function() {
window.removeEventListener('touchstart', forceSafariPlayAudio, false);
}, false);
window.addEventListener('touchstart', forceSafariPlayAudio, false);
</script>
YI wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!