前言

如题:做一个录音文字识别功能,知识点有三个,分别是微信小程序的录音功能、录音文件直传阿里云OSS、使用阿里云的录音文件识别接口返回识别后的文字


一、微信小程序录音

官方文档:微信小程序全局唯一的录音管理器 RecorderManager

wxml:

<view style="padding-top:40%"></view>
<button bindtap="start">开始录音</button>
<!-- <button bindtap="pause">暂停录音</button> -->
<!-- <button bindtap="resume">继续录音</button> -->
<view style="padding-top:10px"></view>
<button bindtap="stop">停止录音并识别</button>
<!-- <button bindtap="play">播放录音[本地]</button> -->
<!-- <button bindtap="play">播放录音[线上]</button> -->
<view style="text-align:center;padding-top:20px">{{text}}</view>

js:需要注意的是,点击开始录音时要判断当前是否获取到了录音权限,如果没有录音权限进行提示,引导用户重新授权

const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()Page({data: {text: '语音识别后文字展示'},onLoad: function () {},//开始录音的时候start: function () {var that = thisconst options = {duration: 100000, //指定录音的时长,单位 mssampleRate: 16000, //采样率numberOfChannels: 1, //录音通道数encodeBitRate: 96000, //编码码率format: 'mp3', //音频格式,有效值 aac/mp3frameSize: 50, //指定帧大小,单位 KB}//开始录音wx.authorize({scope: 'scope.record',success() {console.log("录音授权成功");//第一次成功授权后 状态切换为2that.setData({status: 2,})recorderManager.start(options);recorderManager.onStart(() => {//可以弹出模态框等友好提示console.log('录音开始')});//错误回调recorderManager.onError((res) => {//进行错误提示console.log(res);})},fail() {console.log("第一次录音授权失败");wx.showModal({title: '提示',content: '您未授权录音,功能将无法使用',showCancel: true,confirmText: "授权",confirmColor: "#52a2d8",success: function (res) {if (res.confirm) {//确认则打开设置页面(重点)wx.openSetting({success: (res) => {console.log(res.authSetting);if (!res.authSetting['scope.record']) {//未设置录音授权console.log("未设置录音授权");wx.showModal({title: '提示',content: '您未授权录音,功能将无法使用',showCancel: false})} else {//第二次才成功授权console.log("设置录音授权成功");that.setData({status: 2})}},fail: function () {console.log("授权设置录音失败");}})} else if (res.cancel) {console.log("cancel");}},fail: function () {console.log("openfail");}})}})},//暂停录音-需求不需要暂停pause: function () {recorderManager.pause();recorderManager.onPause((res) => {console.log('暂停录音')})},//继续录音-不需要暂停也就不需要继续resume: function () {recorderManager.resume();recorderManager.onStart(() => {console.log('重新开始录音')});//错误回调recorderManager.onError((res) => {console.log(res);})},//停止录音stop: function () {recorderManager.stop();recorderManager.onStop((res) => {console.log('停止录音', res.tempFilePath)this.getPolicy(res.tempFilePath)})},//播放声音play: function () {innerAudioContext.autoplay = trueinnerAudioContext.src = this.tempFilePath,innerAudioContext.onPlay(() => {console.log('开始播放')})innerAudioContext.onError((res) => {console.log(res.errMsg)console.log(res.errCode)})}
})

二、微信小程序录音直传阿里云OSS

官方文档:微信小程序直传实践

如文档所示,首先进行配置Bucket跨域访问,这个不做解释,其次在微信小程序中配置域名白名单也就是uploadFile和downloadFile合法域名为对应Bucket的外网访问域名

Javascript直传OSS需要提前获取policy,服务端如下:

  public Map<String, String> ossPolicy() {DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");Date date = new Date();String path = "data/" + dateFormat.format(date) + "/";try {long expireTime = 3000;long expireEndTime = System.currentTimeMillis() + expireTime * 1000;Date expiration = new Date(expireEndTime);PolicyConditions policyConds = new PolicyConditions();policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, path);String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);byte[] binaryData = postPolicy.getBytes("utf-8");String encodedPolicy = BinaryUtil.toBase64String(binaryData);String postSignature = ossClient.calculatePostSignature(postPolicy);Map<String, String> respMap = new LinkedHashMap<String, String>();respMap.put("accessid", ossClient.getCredentialsProvider().getCredentials().getAccessKeyId());respMap.put("policy", encodedPolicy);respMap.put("signature", postSignature);respMap.put("dir", path);respMap.put("host", configService.findConfigValueBySuffix(ConfigConstant.CONFIG_SUFFIX_RESOURCE_URL));respMap.put("expire", String.valueOf(expireEndTime / 1000));return respMap;} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}

获取到policy以及签名等后,直传录音文件到阿里云OSS:

  getPolicy: function (path) {wx.request({url: 'https://xxx.com/oss/policy',method: 'GET',success: (res) => {console.log('获取policy成功' + path)this.upload(res, path)}})},upload: function (res, path) {const host = res.data.datas.host;const signature = res.data.datas.signature;const ossAccessKeyId = res.data.datas.accessid;const policy = res.data.datas.policy;//这里的key实际是新起的文件名和路径const key = res.data.datas.dir + Date.now() + '.mp3';wx.uploadFile({url: host,filePath: path,name: 'file', // 必须填file。formData: {key,policy,OSSAccessKeyId: ossAccessKeyId,signature,},success: (res) => {console.log(res);if (res.statusCode === 204) {console.log('上传成功');this.toText(key)}},fail: err => {console.log(err);}});}

三、阿里云录音文字识别极速版

进行录音识别之前需要先创建智能语音交互服务对应的项目,获得AppKey

官方文档:创建智能语音交互服务项目

官方文档:录音文件识别极速版

由于将录音文件直传OSS了,所以不需要将录音文件上传到语音识别里,所以采取第二种方式,使用音频文件链接进行语音识别:

  public ResultBody record2text(String recordUrl) throws Exception {Assert.isBlank(recordUrl, JobErrorInfoEnum.PARAM_NOT_NULL);String prefix = configService.findConfigValueBySuffix(ConfigConstant.CONFIG_SUFFIX_RESOURCE_URL);AccessToken accessToken = new AccessToken(id, secret);accessToken.apply();String token = accessToken.getToken();String fileName = prefix + recordUrl;String format = "mp3";int sampleRate = 16000;String allText = process(fileName, appKey, token, format, sampleRate);Assert.isBlank(allText, JobErrorInfoEnum.RECORD_TRANS_ERROR);return ResultBody.success(allText);}public String process(String fileName, String appKey, String token, String format, int sampleRate) {/*** 设置HTTPS REST POST请求* 1.使用http协议* 2.语音识别服务域名:nls-gateway.cn-shanghai.aliyuncs.com* 3.语音识别接口请求路径:/stream/v1/FlashRecognizer* 4.设置必须请求参数:appkey、token、format、sample_rate*/String request = url;request = request + "?appkey=" + appKey;request = request + "&token=" + token;request = request + "&format=" + format;request = request + "&sample_rate=" + sampleRate;/*** 设置HTTPS头部字段* 发送HTTPS POST请求,返回服务端的响应。** 1.Content-Type:application/octet-stream*/HashMap<String, String> headers = new HashMap<String, String>();String response;if (new File(fileName).isFile()) {headers.put("Content-Type", "application/octet-stream");response = HttpUtil.sendPostFile(request, headers, fileName);} else {headers.put("Content-Type", "application/text");response = HttpUtil.sendPostLink(request, headers, fileName);}String allText = "";if (response != null) {Map map = JsonUtils.json2Map(response);if ((int) map.get("status") == 20000000) {Map result = (Map) map.get("flash_result");List<Map> sentences = (List<Map>) result.get("sentences");if (sentences != null && sentences.size() > 0) {for (Map sentence : sentences) {allText += sentence.get("text");}}}}return allText;}

微信小程序录音直传阿里云OSS并语音识别相关推荐

  1. 微信小程序上传阿里云OSS,返回204,400,403,405,解决方案

    目录 微信小程序上传阿里云 ==OSSAccessKeyId,policy,signature==如何获取呢? 配置Bucket跨域访问 配置外网域名到小程序的域名白名单 上传报错(返回400,403 ...

  2. 微信小程序上传图片到阿里云OSS

    微信小程序代码 1.wxml: <image src="{{userInfo.headImg}}" class="user-head_img" bindt ...

  3. 微信小程序上传图片到阿里云oss方法

    最近开发微信小程序要求上传图片到阿里云oss上,所以就顺手整理一下整个过程啦. 前提 开通oss服务和创建oss存储空间啦(这个就自己去解决吧)下面接入正题: 步骤一:配置 Bucket 跨域 客户端 ...

  4. 微信小程序/vue通过阿里云上传图片

    1.首先前端放入获取上传的组件 微信小程序uview组件: https://www.uviewui.com/components/upload.html vue所使用的element组件: https ...

  5. 微信小程序上传阿里云视频文件流程及代码

    为了微信小程序客服端实现自拍视频能够分享给多个好友,我们需要把小程序自拍的视频存储到服务器,而阿里云在性能和速度上比较不错,所以我们选择了阿里云作服务器. 第一步.微信小程序项目创建 1. 到http ...

  6. Javaweb和微信小程序项目部署阿里云服务器总结(上)

    谈到微信小程序的java后台怎么部署在阿里云服务器上的问题,弯弯绕绕,好多坑,网上的博客资料也特别乱,博主也是在没有任何经验和指导下花了几天的工夫才完成的.这里为了方便大家不踩坑,总结了下整个流程和注 ...

  7. 微信小程序MQTT模拟器 阿里云物联网平台测试

    陈拓 chentuo@ms.xab.ac.cn 2019.09.27/2020.01.20 原文参考:微信小程序-MQTT模拟器 https://www.yuque.com/cloud-dev/iot ...

  8. uniapp vue 微信小程序 前端 直传华为云对象存储OBS

    前言: 因项目服务器性能需要 需要前端直传华为云对象存储 绕过后端 个人在华为云官网SDK文档研究 分享出来 避免大家踩坑 报错定位 web端 报 Error: Network Error   高频问 ...

  9. 小程序中使用阿里云oss上传视频怎么获得视频截图?

    在视频地址后面加上如下的后缀,就可以获取视频内部帧图片,当作封面使用. ?x-oss-process=video/snapshot,t_1000,m_fast ?x-oss-process=video ...

最新文章

  1. java获取当月1号 的时间chuo_java 获取昨天,上个星期一,本月开始时间戳,怎么写呢?...
  2. 人工智能名人堂第54期 | 深度学习鼻祖:Geoffrey Hinton
  3. Eclipse打包工具 FatJAR
  4. C++ with STL(五)queuestacklist
  5. bootstrap轮播图自动播放响应式箭头居中
  6. elasticsearch集群配置文件详述
  7. JavaScript prototype 属性
  8. 为什么要使用Vuex?
  9. 用于MCU,基于FreeRTOS的micro(轻量级)ROS
  10. MySQL无法读表错误的解决方法(MySQL 1018 error)
  11. java 2d 图形_Java学习笔记--Swing2D图形
  12. 微信公众号网页授权代码优化过程(三)
  13. 《Java编程规范学习笔记》
  14. 您的账号与服务器断开连接,节奏大师您解决服务器断开连接的方法(帐号与服务器断开连接怎么办)...
  15. C64x+中断控制器
  16. org.apache.jasper.JasperException: /app/jsonp.jsp(1,2) Page-encoding specified in jsp-property-grou
  17. LZY最喜欢的思维题
  18. 面试时,如何正确介绍自己的项目经验?
  19. 蓝桥杯--第七届决赛:圆圈舞
  20. 为什么我推荐你用语雀记笔记?

热门文章

  1. 轻量型注意力模块:ULSAM
  2. 《第一财经周刊》封面文章:那些忧伤的年轻人
  3. C语言入门校本课程,基于教育虚拟社区的校本课程教学探索
  4. Head first设计模式 第1章阅读笔记
  5. 揭秘 Java帝国的全能家族——Spring的成王之路
  6. DM8:免密登陆配置
  7. Java程序中用JFreeChart制作图形报表-Java基础-Java-编程开发
  8. RabbitListener的“内心深处”
  9. win7用html做桌面,Win7系统如何实现3d桌面?Win7系统立体桌面怎么设置?
  10. 「程序员脱单指南」Guide是如何追到女朋友的?你们要的Girlfriend Guide来啦!