uniapp中inneraudiocontext的使用方法

在uniapp中如何使用innerAudioContext实现音频播放?具体有哪些方法和属性可以调用?如何监听音频的播放状态和错误事件?能否提供一个完整的示例代码?

2 回复

在uni-app中,使用innerAudioContext播放音频。首先创建实例:const audio = uni.createInnerAudioContext(); 然后设置src属性为音频链接,调用audio.play()播放。可监听onPlayonError等事件处理状态。


在 UniApp 中,innerAudioContext 用于创建和控制音频播放实例,适用于播放网络或本地音频文件。以下是基本使用方法:

1. 创建音频实例

const innerAudioContext = uni.createInnerAudioContext();

2. 设置音频源

支持网络 URL 和本地路径:

innerAudioContext.src = 'https://example.com/audio.mp3'; // 网络音频
// 或
innerAudioContext.src = '/static/audio/local.mp3'; // 本地音频

3. 常用属性设置

innerAudioContext.autoplay = false; // 是否自动播放
innerAudioContext.loop = false;     // 是否循环播放
innerAudioContext.volume = 0.5;     // 音量范围 0~1

4. 核心方法

innerAudioContext.play();   // 播放
innerAudioContext.pause();  // 暂停
innerAudioContext.stop();   // 停止(重置进度)
innerAudioContext.seek(10); // 跳转到指定秒数

5. 事件监听

innerAudioContext.onPlay(() => {
  console.log('开始播放');
});

innerAudioContext.onEnded(() => {
  console.log('播放结束');
  innerAudioContext.destroy(); // 销毁实例释放资源
});

innerAudioContext.onError((err) => {
  console.log('播放错误', err);
});

6. 完整示例

export default {
  methods: {
    playAudio() {
      const audio = uni.createInnerAudioContext();
      audio.src = 'https://example.com/sample.mp3';
      audio.autoplay = true;
      
      audio.onPlay(() => {
        console.log('音频开始播放');
      });
      
      audio.onEnded(() => {
        console.log('播放完成');
        audio.destroy();
      });
    }
  }
}

注意事项:

  • 网络音频需配置域名白名单(manifest.json)
  • 使用后建议调用 destroy() 释放资源
  • H5 端自动播放可能受限,需用户交互触发

通过以上方法即可实现基本的音频播放控制功能。

回到顶部