当前位置: 首页 > 后端技术 > Node.js

微信小程序--------语音识别(前端也可以自己玩)

时间:2023-04-03 22:37:45 Node.js

一、背景作为一个前端同学,有时候觉得挺可怜的,复杂的操作都是在服务器端由后端同学完成的。那么,有一天我们想玩一门新技术或者后端同学不理我们,怎么办?无奈.....2.小程序的语音识别接到这个需求,我们澄清了两个问题:小程序的录音支持什么格式?从小程序文档可知:微信小程序录制文件只支持mp3和aac格式科大新闻飞飞平台支持哪些音频格式?Pacm或wav、speex和speex-web格式的iFLYTEK语音听写api3。目的是将小程序的录音转换成科大讯飞可以识别的音频格式importMp3from'@/utils/js-mp3/decode'import{md5}from'@/utils/md5.js'importpcmfrom'pcm-util'recording//获取录音权限this.getRecordAuth()//获取录音对象constthat=this;this.recorderManager=wx.getRecorderManager()this.recorderManager.onStart(()=>{console.log('recorderstart')})//录音格式参数constoptions={duration:11000,sampleRate:32000,numberOfChannels:1,encodeBitRate:64000,格式:'mp3',frameSize:6}this.recorderManager.start(options)this.recorderManager.onStop(res=>{consttempFilePath=res.tempFilePaththat.duration=res.durationconstfs=wx.getFileSystemManager()console.log('recordstop')console.log(res)//从临时文件中读取音频fs.readFile({filePath:tempFilePath,success(res){console.log('readsuccess')that.mp3ToPcm(res.data)},fail(e){console.log('readfail')console.log(e)}})})格式化mp3ToPcm(mp3AB){varthat=thisvardecoder=Mp3.newDecoder(mp3AB)varpcmArrayBuffer=decoder.decode()//与录音相同的格式constfromFormat={channels:1,sampleRate:32000,interleaved:true,float:false,samplesPerFrame:1152,signed:true}//目标音频的格式consttoFormat={channels:1,sampleRate:16000,bitDepth:8,interleaved:true,float:false,samplesPerFrame:576,signed:true}varpcmAB=pcm.convert(pcmArrayBuffer,fromFormat,toFormat)constbase64=wx.arrayBufferToBase64(pcmAB)varmillTime=(新日期().setMilliseconds(0)/1000)+''/**调用科大讯飞平台的语音识别请求参数为应用application的参数*/wx.request({url:'http://api.xfyun.cn/v1/service/v1/iat',方法:'POST',数据:{音频:base64},标头:{'X-Appid':'5be4162d','X-CurTime':millTime,'X-Param':'eyJlbmdpbmVfdHlwZSI6ICJzbXMxNmsiLCJhdWUiOiAicmF3In0=','X-CheckSum':md5('b243cb9e1ea9d9eb40847967a8ebeef2'+millTime+'eyJlbmdpbmVfdHlwZSI6ICJzbXMxNmsiLCJhdWUiOiAicmF3In0='),'content-type':'resplication/x-www-form-urlencoded.('转成功')console.log(res)log(res.data)},fail:function(res){console.log('turnfail')console.log(res)}})}},注:首先在科大讯飞平台申请,申请申请请求参数的文件,语音识别接口文件的录制必须在真机上测试,模拟器是不行的。js-mp3pcm工具包