uniapp录音功能如何实现
在uniapp中如何实现录音功能?需要调用哪些API?是否支持跨平台使用(iOS/Android/小程序)?录音格式和时长有限制吗?求一个完整的示例代码,包括开始录音、停止录音和获取录音文件的操作步骤。
2 回复
使用uniapp的uni.createInnerAudioContext()或plus.audio.getRecorder()实现录音。步骤如下:
- 创建录音实例:
const recorder = uni.createInnerAudioContext() - 开始录音:
recorder.start() - 停止录音:
recorder.stop() - 监听录音完成事件获取文件路径
注意:H5端需使用浏览器API,App端可用原生模块。需在manifest.json中配置录音权限。
在 UniApp 中实现录音功能主要通过 uni.getRecorderManager() API 实现。以下是详细步骤和示例代码:
实现步骤
- 获取录音管理器:使用
uni.getRecorderManager()初始化录音管理器。 - 设置录音参数:通过
start()方法配置采样率、格式等。 - 监听录音事件:包括开始、暂停、结束和错误处理。
- 控制录音操作:开始、暂停、继续和停止录音。
示例代码
// 在 Vue 组件的 methods 或页面中定义
export default {
data() {
return {
recorderManager: null,
isRecording: false,
audioPath: ''
}
},
onLoad() {
// 初始化录音管理器
this.recorderManager = uni.getRecorderManager();
// 监听录音开始事件
this.recorderManager.onStart(() => {
console.log('录音开始');
this.isRecording = true;
});
// 监听录音结束事件
this.recorderManager.onStop((res) => {
console.log('录音结束', res);
this.isRecording = false;
this.audioPath = res.tempFilePath; // 保存录音文件路径
uni.showToast({
title: '录音完成',
icon: 'success'
});
});
// 监听录音错误事件
this.recorderManager.onError((err) => {
console.error('录音错误:', err);
uni.showToast({
title: '录音失败',
icon: 'none'
});
});
},
methods: {
// 开始录音
startRecord() {
this.recorderManager.start({
duration: 60000, // 最长录音时间(ms)
sampleRate: 44100, // 采样率
numberOfChannels: 1, // 声道数
encodeBitRate: 192000, // 编码码率
format: 'mp3' // 音频格式
});
},
// 停止录音
stopRecord() {
this.recorderManager.stop();
},
// 播放录音(可选)
playRecord() {
if (this.audioPath) {
const audio = uni.createInnerAudioContext();
audio.src = this.audioPath;
audio.play();
} else {
uni.showToast({
title: '暂无录音文件',
icon: 'none'
});
}
}
}
}
模板部分(Vue)
<template>
<view>
<button @tap="startRecord" :disabled="isRecording">开始录音</button>
<button @tap="stopRecord" :disabled="!isRecording">停止录音</button>
<button @tap="playRecord">播放录音</button>
</view>
</template>
注意事项
- 权限申请:在
manifest.json中配置麦克风权限(App 端需原生插件支持)。 - 格式兼容性:不同平台支持的音频格式可能不同(如微信小程序仅支持
aac格式)。 - 文件存储:录音文件默认生成临时路径,需及时处理(如上传或保存)。
通过以上代码即可在 UniApp 中实现基础录音功能。实际开发中可根据需求扩展暂停/继续、可视化等功能。

