1、背景html
做爲一名前端同窗有時候感受挺可憐的,複雜的操做都依賴後端同窗在服務器端完成。那麼,有一天咱們本身想玩一個新技術或者後端同窗不搭理咱們,怎麼辦?絕望中.....
2、小程序語音識別前端
接到這個需求,咱們明確兩個問題:
由小程序文檔可知:只支持 mp3格式和 aac格式
微信小程序錄音文檔
git
3. 目標 將小程序的錄音轉爲 科大訊飛能識別的音頻格式github
import Mp3 from '@/utils/js-mp3/decode' import { md5 } from '@/utils/md5.js' import pcm from 'pcm-util' 錄音 // 獲取錄音權限 this.getRecordAuth() // 獲取錄音對象 const that = this; this.recorderManager = wx.getRecorderManager() this.recorderManager.onStart(() => { console.log('recorder start') }) // 錄音的格式參數 const options = { duration: 11000, sampleRate: 32000, numberOfChannels: 1, encodeBitRate: 64000, format: 'mp3', frameSize: 6 } this.recorderManager.start(options) this.recorderManager.onStop(res => { const tempFilePath = res.tempFilePath that.duration = res.duration const fs = wx.getFileSystemManager() console.log('record stop') console.log(res) // 從臨時文件中讀取音頻 fs.readFile({ filePath: tempFilePath, success (res) { console.log('read success') that.mp3ToPcm(res.data) }, fail (e) { console.log('read fail') console.log(e) } }) }) 轉格式 mp3ToPcm (mp3AB) { var that = this var decoder = Mp3.newDecoder(mp3AB) var pcmArrayBuffer = decoder.decode() // 和錄音的格式同樣 const fromFormat = { channels: 1, sampleRate: 32000, interleaved: true, float: false, samplesPerFrame: 1152, signed: true } // 目標音頻的格式 const toFormat = { channels: 1, sampleRate: 16000, bitDepth: 8, interleaved: true, float: false, samplesPerFrame: 576, signed: true } var pcmAB = pcm.convert(pcmArrayBuffer, fromFormat, toFormat) const base64 = wx.arrayBufferToBase64(pcmAB) var millTime = (new Date().setMilliseconds(0) / 1000) + '' /** 調用科大訊飛平臺的語音識別 請求參數都是本身申請應用的參數 */ wx.request({ url: 'http://api.xfyun.cn/v1/service/v1/iat', method: 'POST', data: { audio: base64 }, header: { 'X-Appid': '5be4162d', 'X-CurTime': millTime, 'X-Param': 'eyJlbmdpbmVfdHlwZSI6ICJzbXMxNmsiLCJhdWUiOiAicmF3In0=', 'X-CheckSum': md5('b243cb9e1ea9d9eb40847967a8ebeef2' + millTime + 'eyJlbmdpbmVfdHlwZSI6ICJzbXMxNmsiLCJhdWUiOiAicmF3In0='), 'content-type': 'application/x-www-form-urlencoded' // 默認值 }, success (res) { console.log('turn success') console.log(res) console.log(res.data) }, fail: function (res) { console.log('turn fail') console.log(res) } }) } },
注意:web