通过对App.vue周期事件onHide监听,当进入后台时调用 uni.getBackgroundAudioManager() 播放背景音乐。
android环境下正常播放。
在IOS下由于进入后台之前该段音频没有播放。导致无法正常播放,这是uniapp多年以来留存的bug。
解决办法是,先在应用处于前台时在某个Page的onLoad先播放或者在App的onLuanch先播放。
由于没有调整手机音量提供的接口,需要控制语音播放的位置。在要播放的音频留长1s空音频,可以是停顿。
然后通过参数控制播放的起始位置,如该段音频长度一共10秒,可以在第9秒开始播放。之后就能保持正常,演示代码如下
// onLoad 事件中先播放一次
if (this.g.sysinfo.provider == 2) {
setTimeout(() = > {
console.log('start try sounds');
this.g.sound_startTime = 6;
this.playSound(997);
}, 5000);
}
onHide: function() {
var cur_time = api.timestamp(true);
var last_time = uni.getStorageSync('bg_sound_last_time');
console.log('cur_time', cur_time);
console.log('last_time', last_time);
if (this.g.sysinfo.provider == 2 && fun.is_ios_audit()) {
console.log('ios bg_sound');
if (last_time == '' || cur_time - last_time > 30) {
console.log('ios bg_sound play');
this.playSound(997);
uni.setStorageSync('bg_sound_last_time', cur_time);
}
}
}
// playSound 方法的播放位置实现
const bgAudioMannager = uni.getBackgroundAudioManager();
bgAudioMannager.title = title;
bgAudioMannager.src = res.filePath;
console.log('this.g.sound_startTime', this.g.sound_startTime);
if (this.g.sound_startTime > 0) {
bgAudioMannager.startTime = this.g.sound_startTime;
this.g.sound_startTime = 0;
} else {
bgAudioMannager.startTime = 0;
}