微信小程序通過websocket實時語音識別的實現代碼
更新時間:2020年08月19日 11:25:02 作者:yiyou12138
這篇文章主要介紹了微信小程序通過websocket實時語音識別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
之前在研究百度的實時語音識別,并應用到了微信小程序中,寫篇文章分享一下。
先看看完成的效果吧
前置條件
申請百度實時語音識別key 百度AI接入指南
創(chuàng)建小程序
設置小程序錄音參數
在index.js中輸入
const recorderManager = wx.getRecorderManager() const recorderConfig = { duration: 600000, frameSize: 5, //指定當錄音大小達到5KB時觸發(fā)onFrameRecorded format: 'PCM', //文檔中沒寫這個參數也可以觸發(fā)onFrameRecorded的回調,不過樓主親測可以使用 sampleRate: 16000, encodeBitRate: 96000, numberOfChannels: 1 }
使用websocket連接
linkSocket() { let _this = this //這里的sn是百度實時語音用于排查日志,這里我圖方便就用時間戳了 let sn = new Date().getTime() wx.showLoading({ title: '識別中...' }) recorderManager.start(recorderConfig) //開啟鏈接 wx.connectSocket({ url: 'wss://vop.baidu.com/realtime_asr?sn=' + sn, protocols: ['websocket'], success() { console.log('連接成功') _this.initEventHandle() } }) }, //監(jiān)聽websocket返回的數據 initEventHandle() { let _this = this wx.onSocketMessage((res) => { let result = JSON.parse(res.data.replace('\n','')) if(result.type == 'MID_TEXT'){ _this.tran(result.result, 'value') _this.setData({ textDis: 'none', value: result.result, }) } if(result.type == 'FIN_TEXT'){ let value = _this.data.text let tranStr = value + result.result _this.tran(tranStr, 'text') _this.setData({ value: '', valueEn: '', textDis: 'block', text: tranStr, }) } }) wx.onSocketOpen(() => //發(fā)送數據幀 _this.wsStart() console.log('WebSocket連接打開') }) wx.onSocketError(function (res) { console.log('WebSocket連接打開失敗') }) wx.onSocketClose(function (res) { console.log('WebSocket 已關閉!') }) },
發(fā)送開始、音頻數據、結束幀
wsStart() { let config = { type: "START", data: { appid: XXXXXXXXX,//百度實時語音識別appid appkey: "XXXXXXXXXXXXXXXXXX",//百度實時語音識別key dev_pid: 15372, cuid: "cuid-1", format: "pcm", sample: 16000 } } wx.sendSocketMessage({ data:JSON.stringify(config), success(res){ console.log('發(fā)送開始幀成功') } }) }, wsSend(data){ wx.sendSocketMessage({ data:data, success(res){ console.log('發(fā)送數據幀成功') } }) }, wsStop(){ let _this = this this.setData({ click: true, }) _this.stop() let config = { type: "FINISH" } wx.hideLoading() recorderManager.stop() wx.sendSocketMessage({ data:JSON.stringify(config), success(res){ console.log('發(fā)送結束幀成功') } }) },
小程序錄音回調
onShow: function () { let _this = this recorderManager.onFrameRecorded(function (res){ let data = res.frameBuffer _this.wsSend(data) }) recorderManager.onInterruptionBegin(function (res){ console.log('錄音中斷') _this.wsStopForAcc() }) recorderManager.onStop(function (res){ console.log('錄音停止') }) },
到此這篇關于微信小程序通過websocket實時語音識別的實現代碼的文章就介紹到這了,更多相關微信小程序websocket實時語音識別內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript中使用sencha gridpanel 編輯單元格、改變單元格顏色
ExtJS中的表格功能非常強大,包括了排序、緩存、拖動、隱藏某一列、自動顯示行號、列匯總、單元格編輯等實用功能,通過本篇文章給大家介紹JavaScript中使用sencha gridpanel 編輯單元、改變單元格顏色,感興趣的朋友一起學習2015-11-11