uniapp实现录音功能
模板部分
<view class="voice-button" @touchstart="startRecording" @touchend="stopRecording" @touchcancel="cancelRecording">
<u-icon :name="isRecording ? 'mic' : 'mic'" color="#666666" size="24"></u-icon>
</view>
逻辑部分
onLoad() {
// 初始化录音管理器
this.initRecorderManager();
},
// 初始化录音管理器
initRecorderManager() {
// 创建录音管理器
this.recorderManager = uni.getRecorderManager();
// 监听录音结束事件
this.recorderManager.onStop((res) => {
console.log('录音结束:', res);
// 如果有录音文件,进行语音识别
if (res.tempFilePath) {
this.recognizeSpeech(res.tempFilePath);
console.log(res.tempFilePath, '录音文件');
}
});
// 监听录音错误事件
this.recorderManager.onError((res) => {
console.error('录音错误:', res);
uni.showToast({
title: '录音出错',
icon: 'none'
});
this.isRecording = false;
});
},
// 开始录音
startRecording() {
if (this.loading) return;
this.isRecording = true;
// 配置录音参数
const options = {
duration: 60000, // 最长录音时间,单位ms,最大值60000(1分钟)
sampleRate: 16000, // 采样率
numberOfChannels: 1, // 录音通道数
encodeBitRate: 48000, // 编码码率
format: 'mp3', // 音频格式
frameSize: 50 // 指定帧大小,单位KB
};
// 开始录音
this.recorderManager.start(options);
// 设置超时,防止录音时间过长
this.recordingTimeout = setTimeout(() => {
if (this.isRecording) {
this.stopRecording();
}
}, 60000); // 最长60秒自动停止
// 可以添加震动提示用户开始录音
uni.vibrateShort({
success: function () {
console.log('震动成功');
}
});
},
// 停止录音
stopRecording() {
if (!this.isRecording) return;
// 清除超时计时器
if (this.recordingTimeout) {
clearTimeout(this.recordingTimeout);
this.recordingTimeout = null;
}
// 停止录音
this.recorderManager.stop();
this.isRecording = false;
// 可以再次震动提示用户录音结束
uni.vibrateShort();
},
// 取消录音
cancelRecording() {
if (!this.isRecording) return;
// 清除超时计时器
if (this.recordingTimeout) {
clearTimeout(this.recordingTimeout);
this.recordingTimeout = null;
}
// 停止录音但不处理结果
this.recorderManager.stop();
this.isRecording = false;
uni.showToast({
title: '已取消录音',
icon: 'none'
});
},
// 将语音转换为文字
recognizeSpeech(filePath) {
uni.showLoading({
title: '正在识别...'
});
// 使用 uni.uploadFile 上传音频文件
uni.uploadFile({
url: '你的服务器地址',
filePath: filePath,
name: 'audio_file', // 与服务器端约定的字段名
formData: {
// 如果有其他参数,可以在这里附加
},
header: {
Accept: 'application/json'
},
success: (res) => {
uni.hideLoading();
console.log('语音识别成功:', res);
// 这个地方要加上nextTick才可以响应在页面上面
this.$nextTick(()=>{
this.userInput = res.data
})
// try {
// // if(res.statusCode==200){
// if (this.userInput.length > 0) {
// // 可以选择自动发送或让用户手动发送
// // this.sendMessage(); // 自动发送
// }
// // }else {
// // uni.showToast({
// // title: '语音识别失败',
// // icon: 'none'
// // });
// // }
// } catch (error) {
// uni.showToast({
// title: '解析响应数据失败',
// icon: 'none'
// });
// }
},
fail: (err) => {
uni.hideLoading();
console.error('语音识别请求失败:', err);
uni.showToast({
title: '语音识别请求失败',
icon: 'none'
});
}
});
},
这样结合服务器模型就能实现将语音转换为文字并放入输入框。