@soniox/speech-to-text-web
Version:
Javascript client library for Soniox Speech-to-Text websocket API
2 lines (1 loc) • 7.16 kB
JavaScript
(function(i,n){typeof exports=="object"&&typeof module<"u"?n(exports):typeof define=="function"&&define.amd?define(["exports"],n):(i=typeof globalThis<"u"?globalThis:i||self,n(i["speech-to-text-web"]={}))})(this,function(i){"use strict";var M=Object.defineProperty;var O=(i,n,a)=>n in i?M(i,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[n]=a;var s=(i,n,a)=>O(i,typeof n!="symbol"?n+"":n,a);const n=["Init","Finished","Error","Canceled"],a=["RequestingMedia","OpeningWebSocket","Running","FinishingProcessing"],k=["OpeningWebSocket","Running","FinishingProcessing"];function b(c){return n.includes(c)}function f(c){return a.includes(c)}function g(c){return k.includes(c)}const m="wss://stt-rt.soniox.com/transcribe-websocket",p=1e3,R=120,S='{ "type": "finalize" }',w=()=>({apiKey:"",bufferQueueSize:p}),v={echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,channelCount:1,sampleRate:44100},u=class u{constructor(e){s(this,"_state","Init");s(this,"_options");s(this,"_audioOptions");s(this,"_websocket");s(this,"_mediaRecorder");s(this,"_queuedMessages",[]);s(this,"_hasCallback",e=>{var t;return this._options[e]!=null||((t=this._audioOptions)==null?void 0:t[e])!=null});s(this,"_callback",(e,...t)=>{var o,l,r,d;(l=(o=this._options)[e])==null||l.call(o,...t),(d=(r=this._audioOptions)==null?void 0:r[e])==null||d.call(r,...t)});s(this,"start",async e=>{if(f(this._state))throw new Error("SonioxClient is already active");this._audioOptions={...e};let t;if(e.stream!=null)t=e.stream.clone();else{this._setState("RequestingMedia");try{t=await navigator.mediaDevices.getUserMedia({audio:this._audioOptions.audioConstraints?this._audioOptions.audioConstraints:v})}catch(o){this._onError("get_user_media_failed",o==null?void 0:o.toString())}}if(t==null)throw new Error("Failed to create stream");this._mediaRecorder=new MediaRecorder(t,e.mediaRecorderOptions?e.mediaRecorderOptions:{}),this._queuedMessages=[],this._mediaRecorder.addEventListener("dataavailable",this._onMediaRecorderData),this._mediaRecorder.addEventListener("error",this._onMediaRecorderError),this._mediaRecorder.addEventListener("pause",this._onMediaRecorderPause),this._mediaRecorder.addEventListener("stop",this._onMediaRecorderStop),this._mediaRecorder.start(R),this._setState("OpeningWebSocket"),this._websocket=new WebSocket(this._options.webSocketUri??m),this._websocket.addEventListener("open",this._onWebSocketOpen),this._websocket.addEventListener("error",this._onWebSocketError),this._websocket.addEventListener("message",this._onWebSocketMessage)});s(this,"stop",()=>{var e;this._state=="RequestingMedia"||this._state=="OpeningWebSocket"?(this._closeResources(),this._handleFinished()):this._state=="Running"&&(this._setState("FinishingProcessing"),this._closeSource(),(e=this._websocket)==null||e.send(""))});s(this,"cancel",()=>{b(this._state)||(this._closeResources(),this._setState("Canceled"))});s(this,"finalize",()=>{var e;this._state=="RequestingMedia"||this._state=="OpeningWebSocket"?this._queuedMessages.length<(this._options.bufferQueueSize??p)?this._queuedMessages.push(S):this._onError("queue_limit_exceeded","Queue size exceeded before websocket connection was established."):(this._state=="Running"||this._state=="FinishingProcessing")&&((e=this._websocket)==null||e.send(S))});s(this,"_onMediaRecorderData",async e=>{var t;if(this._state==="OpeningWebSocket")this._queuedMessages.length<(this._options.bufferQueueSize??p)?this._queuedMessages.push(e.data):this._onError("queue_limit_exceeded","Queue size exceeded before websocket connection was established.");else if(this._state==="Running"){const o=await e.data.arrayBuffer();(t=this._websocket)==null||t.send(o)}});s(this,"_onMediaRecorderError",e=>{this._onError("media_recorder_error",e.error??"Unknown error")});s(this,"_onMediaRecorderPause",e=>{this.stop()});s(this,"_onMediaRecorderStop",e=>{this.stop()});s(this,"_onWebSocketOpen",e=>{this._onWebSocketOpenAsync(e)});s(this,"_onWebSocketOpenAsync",async e=>{var r,d;if(this._state!=="OpeningWebSocket"||this._audioOptions==null)return;const t=this._audioOptions;let o;if(typeof this._options.apiKey=="function")try{o=await this._options.apiKey()}catch(_){this._onError("api_key_fetch_failed",_==null?void 0:_.toString());return}else o=this._options.apiKey;if(this._state!=="OpeningWebSocket")return;const l={api_key:o,model:t.model,audio_format:t.audioFormat?t.audioFormat:"auto",sample_rate:t.sampleRate,num_channels:t.numChannels,language_hints:t.languageHints,context:t.context,enable_speaker_diarization:t.enableSpeakerDiarization,enable_language_identification:t.enableLanguageIdentification,enable_endpoint_detection:t.enableEndpointDetection,translation:t.translation,client_reference_id:t.clientReferenceId};(r=this._websocket)==null||r.send(JSON.stringify(l));for(const _ of this._queuedMessages)(d=this._websocket)==null||d.send(_);this._queuedMessages=[],this._setState("Running"),this._callback("onStarted")});s(this,"_onWebSocketError",e=>{g(this._state)&&this._onError("websocket_error","WebSocket error occurred.")});s(this,"_onWebSocketMessage",e=>{if(this._state!="Running"&&this._state!="FinishingProcessing"||this._audioOptions==null)return;const t=JSON.parse(e.data);if(t.error_code!=null||t.error_message!=null){this._onError("api_error",t.error_message,t.error_code);return}this._callback("onPartialResult",t),t.finished&&this._handleFinished()});s(this,"_onError",(e,t,o=void 0)=>{if(this._setState("Error"),this._closeResources(),this._hasCallback("onError"))this._callback("onError",e,t??"Unknown error",o);else throw new Error(`SonioxClient error: ${e}: ${t??"Unknown error"}`)});s(this,"_closeSource",()=>{this._mediaRecorder!=null&&(this._mediaRecorder.removeEventListener("dataavailable",this._onMediaRecorderData),this._mediaRecorder.removeEventListener("error",this._onMediaRecorderError),this._mediaRecorder.removeEventListener("pause",this._onMediaRecorderPause),this._mediaRecorder.removeEventListener("stop",this._onMediaRecorderStop),this._mediaRecorder.stop(),this._mediaRecorder.stream.getTracks().forEach(e=>e.stop()),this._mediaRecorder=null)});s(this,"_closeResources",()=>{this._queuedMessages=[],this._websocket!=null&&(this._websocket.removeEventListener("open",this._onWebSocketOpen),this._websocket.removeEventListener("error",this._onWebSocketError),this._websocket.removeEventListener("message",this._onWebSocketMessage),this._websocket.close(),this._websocket=null),this._closeSource()});if(!u.isSupported)throw"Soniox Speech-to-Text is not supported on this browser.";this._options={...w(),...e},this._audioOptions=null,this._websocket=null,this._mediaRecorder=null}_setState(e){const t=this._state;this._state=e,this._callback("onStateChange",{oldState:t,newState:e})}get state(){return this._state}_handleFinished(){this._closeResources(),this._setState("Finished"),this._callback("onFinished")}};s(u,"isSupported",!!("WebSocket"in window&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia));let h=u;const E=h;i.RecordTranscribe=E,i.SonioxClient=h,i.isActiveState=f,i.isInactiveState=b,i.isWebSocketState=g,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});