公司有开发一个播放音频的网页,因为一些特殊情况,现在需要在小程序webview内嵌该网页。然后就遇到了在苹果和安卓上都无法后台播放的问题,
解决办法:
在iOS端,通过 document.createElement('audio') js方法创建audio标签,就可以正常后台播放
this.audioPlayer = document.createElement('audio')
在Android端
通过webkitAudioContext来进行播放。
var _ctx = new (window.AudioContext || window.webkitAudioContext())()
然后在加载播放器之前加上判断。
export function browerType(resfun) {
var ua = window.navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
// 微信环境下
wx.miniProgram.getEnv(function(res) {
if (res.miniprogram) {
// 小程序环境下逻辑
resfun(2)
} else {
// 非小程序环境下逻辑
resfun(1)
}
})
} else {
resfun(0)
}
}
// 判断是不是苹果手机
export function isIOS() {
var isIphone = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
return isIphone
}
mounted(){
browerType((res) => {
if (res === 2) {
if (!isIOS()) {
setTimeout(() => {
// 使用ctx播放,其他情况使用audio播放
。。。
}, 20)
}
}
})
}