Skip to content

Instantly share code, notes, and snippets.

@aprilandjan
Forked from ufologist/autoplay-audio-ios.html
Created December 20, 2016 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aprilandjan/4954583a664097418e4d5af5557bfed3 to your computer and use it in GitHub Desktop.
Save aprilandjan/4954583a664097418e4d5af5557bfed3 to your computer and use it in GitHub Desktop.
在 iOS 微信浏览器中自动播放 HTML5 audio(音乐) 的正确方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Auto play html audio in iOS WeChat InAppBrowser the right way</title>
</head>
<body>
<h1>在 iOS 微信浏览器中自动播放 HTML5 audio(音乐) 的正确方式</h1>
<p>核心原理: 在微信的JS-API 中 play 一下 audio 即可达到自动播放的目的(应该是微信自己做了处理)</p>
<br>
<br>
<br>
<audio id="bgmusic" src="http://www.w3school.com.cn/i/song.mp3" autoplay preload loop controls></audio>
<!-- 当使用方法1时必须加载 JS-SDK 的 JS 文件, 方法2不需要加载这个 JS -->
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
// 方法1: 现在微信官方已经推出了微信JS-SDK, 最好还是不要使用"野生"方式, 因为不知道什么时候就可以不能用了!
// http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
// 通过config接口注入权限验证配置后, 在 ready 中 play 一下 audio
function autoPlayAudio1() {
wx.config({
// 配置信息, 即使不正确也能使用 wx.ready
debug: false,
appId: '',
timestamp: 1,
nonceStr: '',
signature: '',
jsApiList: []
});
wx.ready(function() {
document.getElementById('bgmusic').play();
});
}
// 方法2: "野生"方法, 借用原来老的 WeixinJSBridge
function autoPlayAudio2() {
window.onload = function() {
// alert(typeof WeixinJSBridge);
WeixinJSBridge.invoke('getNetworkType', {}, function(e) {
// 在这里拿到 e.err_msg, 这里面就包含了所有的网络类型
// alert(e.err_msg);
document.getElementById('bgmusic').play();
});
};
}
// 大家或多或少都知道 iOS Safari 不允许自动播放 audio, 可能已经被坑过了,
// 但微信内嵌的浏览器应该是做了一些定制化, 允许自动播放 audio.
// 测试了以下机型在微信内嵌浏览器中仅需设置 audio autoplay 即可自动播放(audio)音乐, 无需特殊处理.
// * iPhone5 iOS 7.0.6 WeChat 6.2
// * iPhone5s iOS 8.1.2 WeChat 6.3.7
// * iPhone6Plus iOS 8.1.3 WeChat 6.3.7
// * MI1S Android 4.1.2 WeChat 6.3.7
//
// 但是当手机是 iPhone6s iOS 9.1 WeChat 6.3.7 时, 必须做如下特殊处理才能在微信中自动播放(audio)音乐,
// 我可以推测是 iOS 9 的兼容性问题么?
//
autoPlayAudio1(); // 推荐使用方法1
// autoPlayAudio2(); // 也可以试一试方法2
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment