Uniapp集成百度智能云API实现录音转文字(附完整代码)

关键词‌:Uniapp 录音转文字、百度语音识别、语音转文本、Uniapp插件开发

一、功能背景

在移动应用开发中,语音转文字功能广泛应用于会议记录、语音笔记、智能客服等场景。本文将通过‌Uniapp‌结合‌百度智能云语音识别API‌,实现跨端录音并转换为文字的功能。

二、准备工作

1. 百度智能云账号注册

  • 访问百度智能云官网
  • 创建账号并完成实名认证
  • 进入「语音技术」产品页,开通「短语音识别标准版」服务
  • 在「管理控制台」创建应用,获取API KeySecret Key

2. Uniapp项目配置

  • 确保HBuilderX已安装
  • 新建或打开现有Uniapp项目

三、代码实现

<template>
	这里写几个按钮绑定对应的点击事件(开始录音、结束录音、播放录音、语音识别)
</template>
 
<script >
	//录音
	const recorderManager = uni.getRecorderManager();
	//播放录音
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default {
		components: {
	 
		},
		data() {
			return {
				
				token: '',
				adioFileData: '',
				adioSize: '',
				resContent: '',
				luyinStatus: true
			}
		},
		onLoad() {
			let self = this;
			recorderManager.onStop(function(res) {
				//录音后的回调函数
				console.log('recorder stop' + JSON.stringify(res));
				self.voicePath = res.tempFilePath;
				self.Audio2dataURL(res.tempFilePath);
			});
	 
		},
		methods: {
			startLuyin() {
				console.log('开始录音')
				recorderManager.start({
					format: 'amr',
					numberOfChannels: 1,
					sampleRate: 16000
				});
				this.luyinStatus = false
			},
			endLuyin() {
				console.log('录音结束');
				recorderManager.stop();
				this.luyinStatus = true
			},
			startYuyin() {
				console.log("点击转文字")
				var _this = this;
				const AK = "xsM4R*********V2nnOC" //这里填写申请的client_id
				const SK = "sYAuT6*****Cb8qAgkt3" //这里填写申请的client_secret
				//获取token
				uni.request({
				 method: 'POST', // 明确指定POST方法
				 url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
				 headers: {
						'Content-Type': 'application/json',
						'Accept': 'application/json'
				 },
				  success: (res) => {
					console.log("token获取成功", res.data);
					_this.token = res.data.access_token;
					_this.PostData();
				  },
				  fail: (err) => {
					console.error("token请求失败", err);
				  }
				});
			},
			PostData() {
				var postData = {
				format: 'amr', //语音文件的格式,pcm/wav/amr/m4a。不区分大小写。推荐pcm文件
				rate: 16000, // 采样率,16000,固定值 此处文档参数16000,达不到这种高保真音频,故 使用8000
				// dev_pid: 1537,//普通话
				channel: 1, //声道数,仅支持单声道,请填写固定值 1
				cuid: 'breezchd', //用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。
				token: this.token,
				speech: this.adioFileData, //本地语音文件的的二进制语音数据 ,需要进行base64 编码。与len参数连一起使用。
				len: this.adioSize //本地语音文件的的字节数,单位字节 init
				}
				console.log("序列化json",JSON.stringify(postData))
				uni.request({
				  url: 'https://vop.baidu.com/server_api',
				  method: 'POST',
				  data: JSON.stringify(postData), // 需要序列化为JSON字符串
				  headers: {
								'Content-Type': 'application/json',
								'Accept': 'application/json'
						},
				  success: (res) => {
					console.log("识别结果:", res.data);
					// 处理返回结果,示例:
					if (res.data.err_no === 0) {
					  console.log("识别成功:", res.data.result);
					  this.resContent = res.data.result
					} else {
					  console.error("识别失败:", res.data.err_msg);
					}
				  },
				  fail: (err) => {
					console.error("请求失败:", err);
				  }
				});
			},
			Audio2dataURL(path) {
				var _this = this;
				plus.io.resolveLocalFileSystemURL(path, function(entry) {
					entry.file(function(file) {
						var reader = new plus.io.FileReader();
						_this.adioSize = file.size;
						reader.onloadend = function(e) {
							console.log(e.target.result);
							_this.adioFileData = e.target.result.split(",")[1];
						};
						reader.readAsDataURL(file);
						_this.startYuyin()
					}, function(e) {
						alert(e.message)
					})
				})
			},
			//播放
			playVoice() {
				console.log('播放录音');
				if (this.voicePath) {
					innerAudioContext.src = this.voicePath;
					innerAudioContext.play();
				}
			}
		}
} 
</script>
 
<style >

</style>

四、常见问题处理

1. 音频格式问题

  • 百度API支持格式:pcm/wav/amr/m4a
  • 如需转换格式可使用ffmpegmp3-wav

2. 错误码处理

  • 3300: 输入参数不正确 → 检查音频参数
  • 3301: 识别错误 → 重新尝试或降噪处理
  • 3307: 音频质量过差 → 建议用户重新录制
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值