项目有需求,需要集成语音转文字,于是开始研究,一步一个坑

1.集成录音 react-native-audio

2.集成文件操作 react-native-fs

3.集成音频格式转换 react-native-audiotransition。上面两个问题不大,第三步有个坑,rn-audio的录音格式为AAC,需要将AAC转成其他音频格式再传给百度语音,所以需要安装 react-native-audiotransition,安装后如果不翻墙,需要在RN安卓项目的buils.gradle文件添加

allprojects {repositories {mavenLocal()jcenter()maven {// All of React Native (JS, Obj-C sources, Android binaries) is installed from npmurl "$rootDir/../node_modules/react-native/android"}maven {url"https://jitpack.io"}}
}

4.鉴权认证:使用appKey secretKey 访问 https://openapi.baidu.com 换取 token(有效期一个月)

5.百度语音的HTTP POST 请求

下面上全部代码

import React, { Component } from 'react';
import {StyleSheet,Text,View,Dimensions,Platform,TouchableHighlight
} from 'react-native';import { AudioRecorder, AudioUtils } from 'react-native-audio';
import RNFS from 'react-native-fs';
import RNAudiotransition from 'react-native-audiotransition';const ISIPHONEX = Dimensions.get('window').width == 375 && Dimensions.get('window').height == 812export default class Kedaxunfei extends Component {state = {currentTime: 0.0,           //开始录音到现在的持续时间recording: false,           //是否正在录音paused: false,              //是否暂停了录音stoppedRecording: false,    //是否停止了录音finished: false,            //是否完成录音audioPath: AudioUtils.DownloadsDirectoryPath + '/luyin.aac',//路径下的文件名hasPermission: undefined,   //是否获取权限audioSize: 0,                //音频sizeresult: "",                  //语音返回值};prepareRecordingPath(audioPath) {AudioRecorder.prepareRecordingAtPath(audioPath, {SampleRate: 16000,            //采样率Channels: 1,                  //通道AudioQuality: "High",         //音质(Low, Medium, High)AudioEncoding: "aac",         //音频编码(aac编码iOS和Android均支持)AudioEncodingBitRate: 48000,  //音频编码比特率IncludeBase64: true,          //是否是base64格式});}componentDidMount() {//初始化音频格式转化RNAudiotransition.initAudioTransition();//初始化录音AudioRecorder.requestAuthorization().then((isAuthorised) => {this.setState({ hasPermission: isAuthorised });if (!isAuthorised) return;this.prepareRecordingPath(this.state.audioPath);AudioRecorder.onProgress = (data) => {this.setState({ currentTime: Math.floor(data.currentTime) });};AudioRecorder.onFinished = (data) => {// Android callback comes in the form of a promise instead.if (Platform.OS === 'ios') {this._finishRecording(data.status === "OK", data.audioFileURL, data.audioFileSize);}};});}_renderButton(title, onPress, active) {var style = (active) ? styles.activeButtonText : styles.buttonText;return (<TouchableHighlight style={styles.button} onPress={onPress}><Text style={style}>{title}</Text></TouchableHighlight>);}_renderPauseButton(onPress, active) {var style = (active) ? styles.activeButtonText : styles.buttonText;var title = this.state.paused ? "RESUME" : "PAUSE";return (<TouchableHighlight style={styles.button} onPress={onPress}><Text style={style}>{title}</Text></TouchableHighlight>);}async _pause() {if (!this.state.recording) {console.warn('Can\'t pause, not recording!');return;}try {const filePath = await AudioRecorder.pauseRecording();this.setState({ paused: true });} catch (error) {console.error(error);}}async _resume() {if (!this.state.paused) {console.warn('Can\'t resume, not paused!');return;}try {await AudioRecorder.resumeRecording();this.setState({ paused: false });} catch (error) {console.error(error);}}async _stop() {if (!this.state.recording) {console.warn('Can\'t stop, not recording!');return;}this.setState({ stoppedRecording: true, recording: false, paused: false });try {const filePath = await AudioRecorder.stopRecording();if (Platform.OS === 'android') {this._finishRecording(true, filePath);}return filePath;} catch (error) {console.error(error);}}async _record() {if (this.state.recording) {console.warn('Already recording!');return;}if (!this.state.hasPermission) {console.warn('Can\'t record, no permission granted!');return;}if (this.state.stoppedRecording) {this.prepareRecordingPath(this.state.audioPath);}this.setState({ recording: true, paused: false });try {const filePath = await AudioRecorder.startRecording();} catch (error) {console.error(error);}}_finishRecording(didSucceed, filePath, fileSize) {this.setState({ finished: didSucceed });console.log(`Finished recording of duration ${this.state.currentTime} seconds at path: ${filePath} and size of ${fileSize || 0} bytes`);this.timer = setTimeout(() => {//录音文件是aac格式,转写成wav格式RNAudiotransition.audioToStart(AudioUtils.DownloadsDirectoryPath + "/luyin.aac", 'wav', (res) => {console.log(res)//获取音频文件lenRNFS.stat(AudioUtils.DownloadsDirectoryPath + "/luyin.wav").then((StatResult) => {this.setState({audioSize: StatResult.size})})//音频文件转base64RNFS.readFile(AudioUtils.DownloadsDirectoryPath + "/luyin.wav", "base64").then((content) => {//base64传给百度后台let url = "https://vop.baidu.com/pro_api";let params = {"format": "wav",                    //语音文件的格式,pcm、wav、amr、m4a"rate": 16000,                      //采样率,16000,固定值"dev_pid": 80001,                   //普通话"channel": 1,                       //声道数,仅支持单声道,请填写固定值 1"token": "*****",//开放平台获取到的开发者[access_token]"cuid": "baidu_workshop",            //用户唯一标识,用来区分用户,计算UV值。"len": this.state.audioSize,         //本地语音文件的的字节数,单位字节"speech": content,                   //本地语音文件的的二进制语音数据 ,需要进行base64 编码};console.log("content.length" + content.length)fetch(url, {method: 'POST',body: JSON.stringify(params),   //请求体headers: {Accept: "application/json","Content-Type": "application/json",}}).then((response) => response.json()).then((data) => {console.log(data)this.setState({result: data.result})}).catch((error) => {console.log('语音识别错误')});}).catch((err) => {console.log("文件读取失败")});})}, 1000);}render() {return (<View style={styles.container}><View style={styles.controls}>{this._renderButton("RECORD", () => { this._record() }, this.state.recording)}{this._renderButton("STOP", () => { this._stop() })}<Text style={styles.progressText}>{this.state.currentTime}s</Text><Text style={styles.progressText2}>{this.state.result}</Text></View></View>);}
}var styles = StyleSheet.create({container: {flex: 1,backgroundColor: "#2b608a",},controls: {justifyContent: 'center',alignItems: 'center',flex: 1,},progressText: {paddingTop: 50,fontSize: 50,color: "#fff"},progressText2: {paddingTop: 50,fontSize: 20,color: "#fff"},button: {padding: 20},disabledButtonText: {color: '#eee'},buttonText: {fontSize: 20,color: "#fff"},activeButtonText: {fontSize: 20,color: "#B81F00"}});

有描述不清或者有什么不懂得问题可以私信我。

react-native 使用百度语音识别极速版语音转文字相关推荐

  1. 百度语音识别极速版的使用例子(JAVA)

    说明: 1,百度语音极速版,需要事先保存声音文件,然后调用百度接口. 2,关于文件的上传,可以用JSON格式,上传文件的base64编码,也可以用row格式直接上传文件.下面的代码是JSON格式. 3 ...

  2. 百度大脑语音识别极速版~C#开荒攻略

    作者:goJhou 语音识别极速版 API 将60秒以内的完整音频文件识别为文字,适用于近场短语音交互,如手机语音搜索.聊天输入等场景.输入完整音频文件,输出识别结果文字. 采用流式多级截断注意力模型 ...

  3. React native 接入百度AI活体检测、人脸识别 iOS版本

    前期准备工作参考:React native 接入百度AI活体检测.人脸识别 Android版本 iOS配置 1.将FaceSDK里面的文件导入到iOS项目 添加完之后是这样的 2.选择链接C++标准库 ...

  4. React native导入百度地图

    开源地址:https://github.com/lovebing/react-native-baidu-map 今天在React native中导入百度地图组件遇到过许多坑,特此写一篇博客记录踩过的坑 ...

  5. 利用百度语音识别接口将语音转换成文字教程

    一.说明 如果有一个工具能识别音视中的语音并转换成文字输出,由于可以复制粘贴而不需要逐字逐句地打,那我们进行为音频配字幕工作时将会事半功倍. 其中的关键点是音文转换,音文转换其实在很多地方都可以看到比 ...

  6. React Native App设置amp;Android版发布

    React Native系列 <逻辑性最强的React Native环境搭建与调试>  <ReactNative开发工具有这一篇足矣>  <解决React Native ...

  7. 【React Native】集成声网Agora语音通讯

    前言: 公司的产品是一款基于社交的内容聊天软件,需要集成语音通讯功能,在写iOS原生项目时,用到的就是Agora SDK,现在写React Native也直接采用了Agora的库. 集成iOS.And ...

  8. python语音输入转化成文字_利用百度语音识别接口将语音转换成文字教程

    importbase64importjsonimportosimporttimeimportshutilimportrequestsclassBaiduVoiceToTxt():#初始化函数 def ...

  9. iOS中 语音识别功能/语音转文字教程具体解释 韩俊强的博客

    前言:近期研究了一下语音识别,从百度语音识别到讯飞语音识别:首先说一下个人针对两者的看法,讯飞毫无疑问比較专业.识别率也非常高真对语音识别是比較精准的,可是非常多开发人员和我一样期望离线识别,而讯飞离 ...

最新文章

  1. 第一节:网页概述 学习目标 怎样才能学好前端
  2. android 获取 service 信息
  3. html优化网站的方法,利用HTML优化加快网页速度方法介绍
  4. AR独角兽的死亡教训:融资3亿美元后,成投资人提线木偶,营销大于产品技术...
  5. 夺命雷公狗---PHP开发APP接口---1(手动编写json)
  6. QT中图表类QChart之各种缩放/平移
  7. 403 forbidden_[SpringSecurity] 自定义403页面
  8. linux 环境 安装nginx
  9. Linux下 RabbitMQ的安装与配置
  10. Ubuntu18.04设置DNS服务器(可用)
  11. python的类和对象_Python面向对象之类和对象实例详解
  12. 2016.4.5_基于nodejs的聊天室【笔记】
  13. html登录qq页面无法显示,如何解决QQ可以登录网页而无法打开的问题
  14. 【机器学习】完整的机器学习项目演练:第三部分
  15. iOS第三方库-魔窗Mlink的坑
  16. 实时语音视频通话SDK如何实现立体声(一)
  17. 有一种选择叫女程(2)
  18. 正则表达式中反斜杠的另一用法
  19. Final发布 文案+美工展示
  20. 监听器和简单邮件发送

热门文章

  1. 英语分析框架——1300个基本单词介绍
  2. Caeser_Rummikub(一)棋牌的创建
  3. 【校园安防解决方案】如何基于EasyCVR视频能力,搭建校园安防可视化监管平台?
  4. Windows 10 - 复制/扩展显示屏
  5. HDG 深圳站报名 | 平安夜相聚深圳,共话技术干货
  6. 41岁成中国最年轻院士,从农村娃到量子之父,他是科研人的偶像
  7. cocos小游戏实战-04-碰撞检测与NPC渲染
  8. 用计算机做出牙膏盒立体效果制作,用PS软件制作简单有立体感的马赛克立体晶块效果...
  9. 十款实用方便的日志分析工具(建议收藏!!!)
  10. 关闭金融IC卡降级交易,不认真对待你就输了!