uniapp音频使用
音频组件的基本使用
在UniApp中,可以使用<audio>组件或uni.createInnerAudioContext() API来实现音频播放功能。<audio>组件适合简单的音频播放需求,而API方式更适合复杂控制。
<audio src="https://example.com/audio.mp3" controls></audio>
使用uni.createInnerAudioContext()
通过JavaScript API可以更灵活地控制音频播放:
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.src = 'https://example.com/audio.mp3';
innerAudioContext.play();
音频控制方法
play(): 播放音频pause(): 暂停播放stop(): 停止播放seek(position): 跳转到指定位置(单位:秒)
innerAudioContext.pause();
innerAudioContext.seek(30); // 跳转到30秒位置
音频事件监听
可以监听多种音频事件:
innerAudioContext.onPlay(() => {
console.log('开始播放');
});
innerAudioContext.onEnded(() => {
console.log('播放结束');
});
innerAudioContext.onError((res) => {
console.log(res.errMsg);
});
音频属性设置
可以设置多种音频属性:
innerAudioContext.autoplay = true;
innerAudioContext.loop = true;
innerAudioContext.volume = 0.5; // 音量范围0~1
平台差异说明
iOS平台有特殊限制:
- 自动播放需用户交互触发
- 音频资源需在
uni.downloadFile下载后才能播放 - 后台播放需配置manifest.json
// manifest.json
"app-plus": {
"distribute": {
"ios": {
"UIBackgroundModes": ["audio"]
}
}
}
录音功能实现
使用uni.getRecorderManager()实现录音:
const recorderManager = uni.getRecorderManager();
recorderManager.start({
format: 'mp3'
});
recorderManager.stop();
recorderManager.onStop((res) => {
console.log(res.tempFilePath);
});






