uniapp使用百度语音识别语音转文字

HBuilderX已支持讯飞语音识别和百度语音识别,这里讲下百度语音接入

一:首先是百度语音识别申请

这个步骤暂且省略,可以直接移步百度语音api页面自行申请,主要是为了获取语音权限以及AppID、API Key、Secret Key三个参数,可从下图这里查看

二:获取到以上三个参数之后,对HBuilder进行配置

打开项目的manifest.json文件,在“App模块配置”项中勾选“Speech”,如下图输入上面获取到的三个参数

三:上面两个步骤完成后下面就可以品尝了,下面上菜

<template>
	<view class="content">
		<view class="text-area">
			<button @click="startLuyin" v-show="luyinStatus"  class="recordingStyle">开始录音</button>
			<button @click="endLuyin" v-show="!luyinStatus" class="recordingStyle">结束录音</button>
			
		</view>
		<view class="Sound_btn">
			<button @click="playVoice">试听录音</button>
			<button @click="startYuyin">转文字</button>
		</view>
		<view class="reslut_box" v-show="resContent"><p>{{resContent.result}}</p></view>
	</view>
	
</template>

<script >
	//录音
	const recorderManager = uni.getRecorderManager();
//播放录音
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
export default {
	components: {

	},
	data() {
		return {
			title: 'Hello',
			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();
			this.luyinStatus = false
		},
		endLuyin() {
			console.log('录音结束');
			recorderManager.stop();
			this.luyinStatus = true

		},
		startYuyin() {
			var _this = this;
			//获取token
			uni.request({
				url: 'https://openapi.baidu.com/oauth/2.0/token', //仅为示例,并非真实接口地址。
				data: {
					grant_type: 'client_credentials',
					client_id: '',
					client_secret: '',
				},
				header: {
					'content-type': 'application/json;charset=utf-8' //自定义请求头信息
				},
				success: (res) => {
					// console.log(JSON.stringify(res));

					_this.token = res.data.access_token;
					// alert( _this.resContent)
					_this.PostData();
					// _this.$refs.popup.open()
				}
			});


		},
		PostData() {
			var postData = {
				format: 'pcm', //语音文件的格式,pcm/wav/amr/m4a。不区分大小写。推荐pcm文件
				rate: 16000, //	采样率,16000,固定值 此处文档参数16000,达不到这种高保真音频,故 使用8000
				// dev_pid: 1537,//普通话
				channel: 1, //声道数,仅支持单声道,请填写固定值 1
				cuid: 'cuid', //用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。
				token: this.token,
				speech: this.adioFileData, //本地语音文件的的二进制语音数据 ,需要进行base64 编码。与len参数连一起使用。
				len: this.adioSize //本地语音文件的的字节数,单位字节 init
			}
			console.log(JSON.stringify(postData) + '1111')
			//调用语音识别接口
			uni.request({
				url: 'http://vop.baidu.com/server_api', //仅为示例,并非真实接口地址。
				data: postData,
				header: {
					'content-type': 'Content-Type: audio/pcm;rate=16000' //自定义请求头信息
				},
				method: 'POST',
				success: (res) => {
					this.resContent = res.data
					console.log(JSON.stringify(res.data) + "识别结果");
					// this.text = 'request success';
				}
			})
		},
		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)
					// mui.toast("读写出现异常: " + e.message);
				})
			})
		},
		//播放
		playVoice() {
			console.log('播放录音');
			if (this.voicePath) {
				innerAudioContext.src = this.voicePath;
				innerAudioContext.play();
			}
		}
	}
} 
</script>

<style >
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200 rpx;
		width: 200 rpx;
		margin-top: 200 rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50 rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
		margin-top: 10 vh;
	}
	.text-area.recordingStyle {
		width: 100 px;
		height: 100 px;
		border-radius: 50 % ;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 16 px;
		color: # fff;
		background: #409eff;
	}
	.Sound_btn{
		display:flex;
		align-items:center;
		margin:10px 0 0 0;		
	}
	.Sound_btn>button{
		background:none;	
	}
	.title {
		font-size: 36rpx;
		color: # 8 f8f94;
	}
	.reslut_box {
		width: 90 % ;
		background: #409eff10;
		margin:1em 5%;
		padding:0.5em 0;
		border-radius:10px;
	}
	.reslut_box p{
		margin:0 20px;
	}
</style>

已经很详细了,各位吃好喝好

 

  • 3
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
uniapp H5中使用百度语音识别API进行语音文字可以按照以下步骤来进行: 1. 首先需要在百度AI开放平台上注册账号,创建应用,获取API Key和Secret Key。 2. 在uniapp项目中,引入百度语音识别API的SDK文件,可在百度AI开放平台上下载。 3. 在uniapp项目中,使用uni-app提供的录音组件进行录音,并将录音文件传递给百度语音识别API进行处理。 4. 将百度语音识别API返回的结果展示在页面上。 下面是一个简单的示例代码: ```html <!-- 引入录音组件 --> <uni-audio-recorder v-model="audioSrc" @success="onRecordSuccess" @error="onRecordError" /> <!-- 按钮触发识别 --> <button @click="startRecognize">开始识别</button> <div>{{result}}</div> ``` ```javascript export default { data() { return { // 录音文件路径 audioSrc: '', // 识别结果 result: '' } }, methods: { // 录音成功回调 onRecordSuccess(res) { this.audioSrc = res.tempFilePath }, // 录音失败回调 onRecordError(res) { uni.showToast({ title: '录音失败' }) }, // 开始识别 startRecognize() { // 引入百度语音识别API const SpeechRecognizer = uni.requireNativePlugin('uni-speech-recognizer') // 配置参数 const options = { apiKey: 'yourApiKey', secretKey: 'yourSecretKey', audioSource: this.audioSrc, audioFormat: 'wav', devPid: 1536 // 中文普通话 } // 调用API进行识别 SpeechRecognizer.recognizer(options, (res) => { this.result = res.result }, (err) => { uni.showToast({ title: '识别失败' }) }) } } } ``` 需要注意的是,使用uni-app提供的录音组件进行录音时,需要在manifest.json文件中添加权限声明: ```json { "permission": { "scope.record": { "desc": "用于录制和识别语音" } } } ``` 另外,需要在uni-app的manifest.json文件中添加nativePlugins声明,才能使用uni.requireNativePlugin引入百度语音识别API: ```json { "nativePlugins": [ { "name": "uni-speech-recognizer", "version": "1.0.0", "provider": "uni" } ] } ``` 希望这个示例能够帮助到您。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值