背景音频播放uni.getBackgroundAudioManager()没有OffEnded等方法,绑定的事件无法取消。这样导致多次进入页面重复绑定多个事件,难以进行优化。期待官方予以完善。

TADPOLE
- 发布:2021-11-03 15:01
- 更新:2021-11-03 15:37
- 阅读:1083
背景音频播放uni.getBackgroundAudioManager()没有OffEnded等方法,绑定的事件无法取消
分类:uni-app
1 个回复
TADPOLE (作者)
找到一个变通的处理方法:
1.包装一个audioUtils工具:
···
let audioContext=null;
let canPlayCallback=null;
let endedCallback=null;
let timeUpdateCallback=null;
function onCanplay(e) {
canPlayCallback = e;
}
function onEnded(e) {
endedCallback = e;
}
function onTimeUpdate(e) {
timeUpdateCallback = e;
}
function initContext() {
if (audioContext!=null) {
return audioContext;
}
audioContext = uni.getBackgroundAudioManager();
audioContext.onTimeUpdate((e) => {
if (timeUpdateCallback!=null) {
console.log('onTimeUpdate callback ')
timeUpdateCallback();
}
});
audioContext.onCanplay((e) => {
if (canPlayCallback!=null) {
console.log('onCanplay callback ')
canPlayCallback();
}
});
audioContext.onEnded((e) => {
if (endedCallback!=null) {
console.log('onEnded callback ')
endedCallback();
}
});
return audioContext;
}
const audioUtils = {
initContext, onCanplay, onEnded, onTimeUpdate
}
export default audioUtils;
···
audioContext = audioUtils.initContext();
不再直接调用
audioContext = uni.getBackgroundAudioManager();
绑定事件时使用
audioUtils.onTimeUpdate((e) => {....});
不再使用
audioContext.onTimeUpdate((e) => {....});
亲测有效!
原理:运用import导入对象的静态特性,audioUtils绑定新事件后原事件被覆盖,不会再出现重复。