asr.min.js
12.5 KB
const recorderManager=wx.getRecorderManager();let recorderSpeechRecognizeInstance;const guid=()=>{return"xxxxxxxx-xxxx-5xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0,n=e==="x"?t:t&3|8;return n.toString(16)})};function formatSignString(e,t){let n="";let i="asr.cloud.tencent.com/asr/v2/";if(e["appid"]){i+=e["appid"]}else{return""}const r=Object.keys(t);r.sort();for(const s in r){n+=`&${r[s]}=${t[r[s]]}`}return`${i}?${n.slice(1)}`}function getServerTime(e){return new Promise((t,n)=>{try{wx.request({url:"https://asr.cloud.tencent.com/server_time",data:e,method:"GET",dataType:"json",success:e=>{if(e&&e.data){t(e&&e.data)}else{n(e)}},fail:e=>{n(e)}})}catch(e){n(e)}})}async function createQuery(e,t){const n={};const i=await getServerTime();n["secretid"]=e.secretid||"";n["engine_model_type"]=e.engine_model_type||"16k_zh";n["timestamp"]=parseInt(i);n["expired"]=parseInt(i)+24*60*60;n["nonce"]=Math.round(i/100);n["voice_id"]=t;n["voice_format"]=e["voice_format"]||8;e.hasOwnProperty("hotword_id")&&(n["hotword_id"]=e.hotword_id);e.hasOwnProperty("customization_id")&&(n["customization_id"]=e.customization_id);e.hasOwnProperty("needvad")&&(n["needvad"]=e.needvad);e.hasOwnProperty("filter_dirty")&&(n["filter_dirty"]=e.filter_dirty);e.hasOwnProperty("filter_modal")&&(n["filter_modal"]=e.filter_modal);e.hasOwnProperty("filter_punc")&&(n["filter_punc"]=e.filter_punc);e.hasOwnProperty("convert_num_mode")&&(n["convert_num_mode"]=e.convert_num_mode);e.hasOwnProperty("word_info")&&(n["word_info"]=e.word_info);e.hasOwnProperty("vad_silence_time")&&(n["vad_silence_time"]=e.vad_silence_time);e.hasOwnProperty("hotword_list")&&(n["hotword_list"]=e.hotword_list);e.hasOwnProperty("reinforce_hotword")&&(n["reinforce_hotword"]=e.reinforce_hotword);return n}async function getSignStr(e,t){const n=await createQuery(e,t);return formatSignString(e,n)}export class SpeechRecognizer{constructor(e){this.appid="";this.secretid="";this.socket=null;this.isSignSuccess=false;this.isSentenceBegin=false;this.query={};this.signCallback=null;this.voiceId="";this.isLog=e}stop(){if(this.socket&&this.socket.readyState===1){this.socket.send({data:JSON.stringify({type:"end"})})}}async getUrl(e,t){const n=await getSignStr(e,t);if(!n){return false}return`${n}&signature=${encodeURIComponent(this.signCallback(n))}`}async start(r){this.appid=r.appid||"";this.secretid=r.secretid||"";this.socket=null;this.isSignSuccess=false;this.isSentenceBegin=false;this.query={...r};this.voiceId=guid();function s(e){const t=e.words;const n=e.sigBytes;const i=new Uint8Array(n);for(let e=0;e<n;e++){i[e]=t[e>>>2]>>>24-e%4*8&255}return i}function e(e){const t=r.secretkey;const n=CryptoJS.HmacSHA1(e,t);const i=s(n);return wx.arrayBufferToBase64(i)}this.signCallback=r.signCallback||e;const t=await this.getUrl(this.query,this.voiceId);this.isLog&&console.log("get url",t,this.voiceId);if(!t){this.OnError({code:6002,message:"鉴权失败",voice_id:this.voiceId});return}const n={url:`wss://${t}`,header:{}};if(r.token){n["header"]["X-TC-Token"]=r.token}this.socket=wx.connectSocket(n);this.socket.onMessage(e=>{const t=JSON.parse(e.data||null);if(t.code!==0){this.OnError(t);this.socket&&this.socket.close()}else{if(!this.isSignSuccess){this.OnRecognitionStart(t);this.isSignSuccess=true}if(t.final===1){this.OnRecognitionComplete(t);return}if(t.result){if(t.result.slice_type===0){this.OnSentenceBegin(t);this.isSentenceBegin=true}else if(t.result.slice_type===2){if(!this.isSentenceBegin){this.OnSentenceBegin(t)}this.OnSentenceEnd(t)}else{this.OnRecognitionResultChange(t)}}}});this.socket.onError(e=>{this.isLog&&console.log("socket onError",e,this.voiceId);this.socket&&this.socket.close();this.OnError({code:6e3,message:e,voice_id:this.voiceId});this.socket=null});this.socket.onClose(e=>{this.socket=null})}write(e){if(!this.socket||this.socket.readyState!==1){return}this.socket.send({data:e,success:e=>{},fail:e=>{this.isLog&&console.log("socket send error",e,this.voiceId);this.OnError({code:6e3,message:e,voice_id:this.voiceId})}})}OnRecognitionStart(e){}OnSentenceBegin(e){}OnRecognitionResultChange(){}OnSentenceEnd(){}OnRecognitionComplete(){}OnError(){}}class Recorder{constructor(){this.canStop=false;if(!Recorder.instance){Recorder.instance=this}return Recorder.instance}start(e,t){this.isLog=t;function n(e){switch(String(e)){case"1":return"pcm";case"8":return"mp3";default:return"mp3"}}const i={duration:e.duration||6e5,sampleRate:16e3,numberOfChannels:1,encodeBitRate:64e3,format:n(e.voice_format),frameSize:e.frameSize||.32};this.isLog&&console.log("recorderParams: ",i);recorderManager.start(i);recorderManager.onStart(e=>{this.isLog&&console.log("recorderManager is start");this.canStop=true});recorderManager.onStop(e=>{this.isLog&&console.log("recorderManager is stop: ",e);this.canStop=false;this.OnStop(e)});recorderManager.onError(e=>{this.isLog&&console.log("recorderManager is error: ",e);this.canStop=false;this.OnError(e);this.stop()});recorderManager.onFrameRecorded(e=>{this.OnReceivedData(e.frameBuffer);this.OnFrameRecorded(e)});recorderManager.onInterruptionBegin(()=>{this.stop();this.OnInterruptionBegin()});recorderManager.onInterruptionEnd(()=>{this.stop();this.OnInterruptionEnd()})}stop(){if(recorderManager&&this.canStop){recorderManager.stop()}}OnReceivedData(e){}OnError(e){}OnStop(e){}OnInterruptionBegin(){}OnInterruptionEnd(){}OnFrameRecorded(){}}class RecorderSpeechRecognizer{constructor(e){this.isLog=e}init(){this.speechRecognizer=null;this.isCanSendData=false;this.audioData=[]}start(r){this.isLog&&console.log("start function is click");if(this.recorder){return false}this.init();this.recorder=new Recorder;const e={duration:r.duration,frameSize:r.frameSize,voice_format:r.voice_format};this.recorder.start(e,this.isLog);this.audioData=[];this.recorder.OnReceivedData=e=>{this.audioData.push(...new Int8Array(e));const t=r["engine_model_type"].includes("8k")?640:1280;if(this.isCanSendData&&this.audioData.length>t){const n=this.audioData.splice(0,t);const i=new Int8Array(n);this.speechRecognizer.write(i.buffer)}};this.recorder.OnFrameRecorded=e=>{this.OnFrameRecorded(e)};this.recorder.OnInterruptionBegin(()=>{this.isLog&&console.log("recorderOnInterruptionBegin");this.OnInterruptionBegin()});this.recorder.OnInterruptionEnd(()=>{this.isLog&&console.log("recorderOnInterruptionEnd");this.OnInterruptionEnd()});this.recorder.OnStop=e=>{this.recorder=null;if(this.isCanSendData&&this.audioData.length>0){this.speechRecognizer&&this.speechRecognizer.write(new Int8Array(this.audioData).buffer);this.audioData=[]}this.OnRecorderStop(e);if(this.speechRecognizer){this.speechRecognizer.stop()}};this.recorder.OnError=e=>{this.stop();this.OnError(e)};if(!this.speechRecognizer){this.speechRecognizer=new SpeechRecognizer(this.isLog)}this.speechRecognizer.OnRecognitionStart=e=>{this.isLog&&console.log("OnRecognitionStart",e);this.OnRecognitionStart(e);this.isCanSendData=true};this.speechRecognizer.OnSentenceBegin=e=>{this.isLog&&console.log("OnSentenceBegin",e);this.OnSentenceBegin(e)};this.speechRecognizer.OnRecognitionResultChange=e=>{this.OnRecognitionResultChange(e)};this.speechRecognizer.OnSentenceEnd=e=>{this.OnSentenceEnd(e)};this.speechRecognizer.OnRecognitionComplete=e=>{this.isLog&&console.log("OnRecognitionComplete",e);this.OnRecognitionComplete(e);this.isCanSendData=false};this.speechRecognizer.OnError=e=>{this.isLog&&console.log("OnError",e);this.OnError(e);this.isCanSendData=false;setTimeout(()=>{if(this.recorder){this.recorder.stop()}},500)};this.speechRecognizer.start(r)}stop(){this.isLog&&console.log("stop function is click");if(this.recorder){this.recorder.stop()}}OnRecognitionStart(e){}OnSentenceBegin(e){}OnRecognitionResultChange(){}OnSentenceEnd(){}OnRecognitionComplete(){}OnError(){}OnRecorderStop(){}OnInterruptionBegin(){}OnInterruptionEnd(){}OnFrameRecorded(){}}export function getRecorderSpeechRecognizer(e){if(!recorderSpeechRecognizeInstance){recorderSpeechRecognizeInstance=new RecorderSpeechRecognizer(e)}return recorderSpeechRecognizeInstance}var CryptoJS=CryptoJS||function(c,n){var e={},t=e.lib={},i=function(){},r=t.Base={extend:function(e){i.prototype=this;var t=new i;e&&t.mixIn(e);t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)});t.init.prototype=t;t.$super=this;return t},create:function(){var e=this.extend();e.init.apply(e,arguments);return e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},a=t.WordArray=r.extend({init:function(e,t){e=this.words=e||[];this.sigBytes=t!=n?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,n=e.words,i=this.sigBytes;e=e.sigBytes;this.clamp();if(i%4)for(var r=0;r<e;r++)t[i+r>>>2]|=(n[r>>>2]>>>24-8*(r%4)&255)<<24-8*((i+r)%4);else if(65535<n.length)for(r=0;r<e;r+=4)t[i+r>>>2]=n[r>>>2];else t.push.apply(t,n);this.sigBytes+=e;return this},clamp:function(){var e=this.words,t=this.sigBytes;e[t>>>2]&=4294967295<<32-8*(t%4);e.length=c.ceil(t/4)},clone:function(){var e=r.clone.call(this);e.words=this.words.slice(0);return e},random:function(e){for(var t=[],n=0;n<e;n+=4)t.push(4294967296*c.random()|0);return new a.init(t,e)}}),s=e.enc={},o=s.Hex={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],i=0;i<e;i++){var r=t[i>>>2]>>>24-8*(i%4)&255;n.push((r>>>4).toString(16));n.push((r&15).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],i=0;i<t;i+=2)n[i>>>3]|=parseInt(e.substr(i,2),16)<<24-4*(i%8);return new a.init(n,t/2)}},h=s.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],i=0;i<e;i++)n.push(String.fromCharCode(t[i>>>2]>>>24-8*(i%4)&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],i=0;i<t;i++)n[i>>>2]|=(e.charCodeAt(i)&255)<<24-8*(i%4);return new a.init(n,t)}},d=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(h.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return h.parse(unescape(encodeURIComponent(e)))}},l=t.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new a.init;this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e));this._data.concat(e);this._nDataBytes+=e.sigBytes},_process:function(e){var t=this._data,n=t.words,i=t.sigBytes,r=this.blockSize,s=i/(4*r),s=e?c.ceil(s):c.max((s|0)-this._minBufferSize,0);e=s*r;i=c.min(4*e,i);if(e){for(var o=0;o<e;o+=r)this._doProcessBlock(n,o);o=n.splice(0,e);t.sigBytes-=i}return new a.init(o,i)},clone:function(){var e=r.clone.call(this);e._data=this._data.clone();return e},_minBufferSize:0});t.Hasher=l.extend({cfg:r.extend(),init:function(e){this.cfg=this.cfg.extend(e);this.reset()},reset:function(){l.reset.call(this);this._doReset()},update:function(e){this._append(e);this._process();return this},finalize:function(e){e&&this._append(e);return this._doFinalize()},blockSize:16,_createHelper:function(n){return function(e,t){return new n.init(t).finalize(e)}},_createHmacHelper:function(n){return function(e,t){return new u.HMAC.init(n,t).finalize(e)}}});var u=e.algo={};return e}(Math);(function(){var e=CryptoJS,t=e.lib,n=t.WordArray,i=t.Hasher,d=[],t=e.algo.SHA1=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var n=this._hash.words,i=n[0],r=n[1],s=n[2],o=n[3],c=n[4],a=0;80>a;a++){if(16>a)d[a]=e[t+a]|0;else{var h=d[a-3]^d[a-8]^d[a-14]^d[a-16];d[a]=h<<1|h>>>31}h=(i<<5|i>>>27)+c+d[a];h=20>a?h+((r&s|~r&o)+1518500249):40>a?h+((r^s^o)+1859775393):60>a?h+((r&s|r&o|s&o)-1894007588):h+((r^s^o)-899497514);c=o;o=s;s=r<<30|r>>>2;r=i;i=h}n[0]=n[0]+i|0;n[1]=n[1]+r|0;n[2]=n[2]+s|0;n[3]=n[3]+o|0;n[4]=n[4]+c|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,i=8*e.sigBytes;t[i>>>5]|=128<<24-i%32;t[(i+64>>>9<<4)+14]=Math.floor(n/4294967296);t[(i+64>>>9<<4)+15]=n;e.sigBytes=4*t.length;this._process();return this._hash},clone:function(){var e=i.clone.call(this);e._hash=this._hash.clone();return e}});e.SHA1=i._createHelper(t);e.HmacSHA1=i._createHmacHelper(t)})();(function(){var e=CryptoJS,h=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init;"string"==typeof t&&(t=h.parse(t));var n=e.blockSize,i=4*n;t.sigBytes>i&&(t=e.finalize(t));t.clamp();for(var r=this._oKey=t.clone(),s=this._iKey=t.clone(),o=r.words,c=s.words,a=0;a<n;a++)o[a]^=1549556828,c[a]^=909522486;r.sigBytes=s.sigBytes=i;this.reset()},reset:function(){var e=this._hasher;e.reset();e.update(this._iKey)},update:function(e){this._hasher.update(e);return this},finalize:function(e){var t=this._hasher;e=t.finalize(e);t.reset();return t.finalize(this._oKey.clone().concat(e))}})})();