小程序弃用了audio
组件,转而提供了2种音频播放的方式 :createInnerAudioContext
和 getBackgroundAudioManager
所区别的是:
backgroundAudioManager 是 全局唯一的背景音频管理器
如果需要音乐类似QQ音乐那样,小程序在后台时,仍然在播放音乐 请使用 getBackgroundAudioManager
否则应该 使用普通音频API createInnerAudioContext
。
踩的坑
我在使用 getBackgroundAudioManager
的时候出现了2种错误。
- setBackgroundAudioState:fail title is nil!;at api setBackgroundAudioState …
- setBackgroundAudioState fail jsapi has no permission
对于第一个,需要我们设置几个属性(虽然我们可能用不上,但是必须要设置)
innerAudioContext.title = this.lyricTitle; //有值,但是不展示
innerAudioContext.singer = '暂无'; //有值,但是不展示
innerAudioContext.coverImgUrl = this.lyricCover; //有值,但是不展示
innerAudioContext.src = this.src;
对于第二个,素我在使用 onPrev 和 onNext (iOS only)的时候出现的一个问题。
这里我在微信开放社区找到了答案 https://developers.weixin.qq.com/community/develop/doc/0000c82f83c2c85006199bd7a51c00
因为我在切换音乐的时候设置了 stop() 方法,只需要去除或者在 onPrev 的时候不执行就可以了。
innerAudioContext.onNext(()=>{
console.log("下一首");
this.changeAudio(2,true);
})
...
changeAudio(type,isIOS){
if(!isIOS){ //ios 端后台播放,stop后会报错
/* 清空当前内容 */
this.innerAudioContext.src="1"; // 这里需要穿https 的路径
this.innerAudioContext.title = '暂无'; //有值,但是不展示
this.innerAudioContext.singer = '暂无'; //有值,但是不展示
this.innerAudioContext.coverImgUrl = 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/audio/music.jpg'; //有值,但是不展示
this.innerAudioContext.stop();
this.innerAudioContext.onStop(function(){
console.log('停止播放');
})
}
}