uni-app 背景音乐uni.getBackgroundAudioManager() 多次加载onPlay等方法

uni-app 背景音乐uni.getBackgroundAudioManager() 多次加载onPlay等方法

开发环境 版本号 项目创建方式
Windows windows10专业版 HBuilderX

产品分类:uniapp/App

PC开发环境操作系统:Windows

PC开发环境操作系统版本号:windows10专业版

HBuilderX类型:正式

HBuilderX版本号:3.2.13

手机系统:Android

手机系统版本号:Android 10

手机厂商:华为

手机机型:华为P40

页面类型:vue

vue版本:vue2

打包方式:云端

App下载地址或H5网址: https://ide.dcloud.net.cn/build/download/cdf08340-4363-11ec-9fe1-2dce755a70f7

示例代码:

this.audio = uni.getBackgroundAudioManager(); this.audio.src = ‘’ this.audio.onPlay(() => { console.log(‘开始播放’); this.rotate() }); this.audio.onStop(() => { console.log(‘停止播放’); });

this.audio.onPause(() => {
console.log(‘暂停播放’);
clearInterval(InterVal)
});
this.audio.onEnded(() => {
//初始化 需要的参数
console.log(‘自然播放结束事件’);
if(this.isCurrent && this.isCurrent == 1){
console.log(‘进去定时’)
clearInterval(this.timeSet)
this.isPlay = false;
this.isCurrent = 0
this.timedPause = true
}else {
console.log(‘下一首’)
this.jump(2)
}
});
this.audio.onError((res) => {
console.log(res.errMsg);
console.log(res.errCode);
});


更多关于uni-app 背景音乐uni.getBackgroundAudioManager() 多次加载onPlay等方法的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复

真机遇到这个问题,请问解决了么?

更多关于uni-app 背景音乐uni.getBackgroundAudioManager() 多次加载onPlay等方法的实战教程也可以访问 https://www.itying.com/category-93-b0.html


请问怎么解决的

再次进入时,做个判断,audio是不是已经有了

请问解决了吗

在 uni-app 中使用 uni.getBackgroundAudioManager() 时,多次加载 onPlay 等方法确实会导致事件监听重复绑定,这是常见问题。你的代码中每次调用都会创建新的监听器,造成事件多次触发。

解决方案:

  1. 单例模式管理:在页面或全局只初始化一次 BackgroundAudioManager,避免重复创建。

  2. 先移除再绑定:在绑定事件前先调用 off 方法移除已有监听(注意:部分基础库版本可能不支持 off,需测试兼容性)。

  3. 使用条件初始化:通过变量控制仅初始化一次。

修改建议:

// 在 data 或页面顶部定义管理变量
data() {
  return {
    audio: null,
    audioInited: false
  }
},

// 初始化方法
initAudioManager() {
  if (this.audioInited) return;
  
  this.audio = uni.getBackgroundAudioManager();
  
  // 先尝试移除已有监听(如果支持)
  if (this.audio.off) {
    this.audio.off('play');
    this.audio.off('pause');
    this.audio.off('stop');
    this.audio.off('ended');
    this.audio.off('error');
  }
  
  // 绑定事件监听
  this.audio.onPlay(() => {
    console.log('开始播放');
    this.rotate();
  });
  
  this.audio.onStop(() => {
    console.log('停止播放');
  });
  
  this.audio.onPause(() => {  
    console.log('暂停播放');  
    clearInterval(InterVal);  
  });   
  
  this.audio.onEnded(() => {  
    if(this.isCurrent && this.isCurrent == 1){  
      clearInterval(this.timeSet);  
      this.isPlay = false;  
      this.isCurrent = 0;  
      this.timedPause = true;  
    } else {  
      this.jump(2);  
    }  
  });  
  
  this.audio.onError((res) => {  
    console.log(res.errMsg, res.errCode);  
  });
  
  this.audioInited = true;
},

// 在需要时调用初始化
mounted() {
  this.initAudioManager();
}
回到顶部