Javascript SDK
Overview
The skd in javascript is a lightweight client to interact with the Speaqr api in real time. It provides the programmer with access to the methods of the api giving him certain functionalities. It is compatible with browser and Node.js environmentsThe package is published in npm.To use the SDK you need a valid api key. To obtain it, please contact us through the contracting form.Installation
Via npm
npm install @speaqr/javascript-sdk
Via cdn
<script src="https://unpkg.com/@speaqr/javascript-sdk@latest/dist/sdk.min.js"></script>
Download the files
sdk.jssdk.min.js
Instantiate the class
The Speaqr SDK can be instantiated and used in a variety of environments, such as browsers, Node.js and modules imported from a CDN. The following explains the different ways to initialize it depending on the environment.In the npm package you have examples with specific languages in the folder:dist/examples/howInstantiateSdk
Browsers (Using CDN)
The SDK is available through a CDN to be used directly in the browser, without prior installation.
<html>
<script src="https://unpkg.com/@speaqr/javascript-sdk@latest/dist/sdk.min.js"></script>
<script src="https://my_code.js"></script>
</html>
// my_code.js
const sdk = new SpeaqrSDK({
apiKey: "YOUR_API_KEY",
showLogs: true
});
Node.js
In a Node.js environment, you can install the SDK via npm and import it with require or import depending on your configuration.
// Using CommonJS (require)
const SpeaqrSDK = require("@speaqr/javascript-sdk");
const sdk = new SpeaqrSDK({
apiKey: "YOUR_API_KEY",
showLogs: true
});
TypeScript
If you work in a TypeScript environment, the SDK includes type definitions(index.d.ts)
that make it easy to use the SDK with strong typing.
import SpeaqrSDK from "@speaqr/javascript-sdk";
const sdk = new SpeaqrSDK({
apiKey: "YOUR_API_KEY",
showLogs: true
});
ES Module Environments (ESM)
If you are working in an environment that supports ES modules, such as modern browsers or a development environment with ESM support, you can useimport.
import SpeaqrSDK from "https://unpkg.com/@speaqr/javascript-sdk@latest/dist/sdk.min.js";
const sdk = new SpeaqrSDK({
apiKey: "YOUR_API_KEY",
showLogs: true
});
RequireJS
The SDK is compatible with loading systems such as RequireJS.
<html>
<script data-main="app" src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
<script src="https://my_code.js"></script>
</html>
// my_code.js
require(["https://unpkg.com/@speaqr/javascript-sdk@latest/dist/sdk.min.js"],
function(SpeaqrSDK) {
const sdk = new SpeaqrSDK({
apiKey: "YOUR_API_KEY",
showLogs: true
});
Builders and destruction
TheSpeaqrSDK
class includes two forms of instantiation: a synchronous constructor and an asynchronous static create
method. In addition, it provides the destroy()
method to free resources when the SDK instance is no longer needed.Synchronous constructor
This constructor creates an instance of the SDK immediately. It requires the api key to be provided, but does not perform validations at initialization time.Parameters
Example
const sdk = new SpeaqrSDK({
apiKey: "YOUR_API_KEY",
showLogs: true
});
Asynchronous builder
This static method returns a promise that resolves to an instance of the SDK, validating the api key before completing the initialization.Parameters
Example
try {
const sdk = await SpeaqrSDK.create({
apiKey: "YOUR_API_KEY",
showLogs: true
});
console.log("SDK initialized:", sdk);
} catch (error) {
console.error("Error initializing SDK:", error);
}
Destroy()
method (resource release)
The SDK provides the destroy() method to free resources when the instance is no longer needed. The method is asynchronous and returns a promise. This method:- Closes active socket connections.
- Removes listeners from registered events.
- Releases internal references to avoid memory leaks.
- Overrides all SDK methods to prevent unwanted uses after destruction.
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
// SDK use
sdk.languages()
.then((languages) => console.log("Supported languages:", languages))
.catch((error) => console.error(error));
//When the SDK is no longer needed
await sdk.destroy();
If you try to call a method after the instance has been destroyed, an error will be thrown:
sdk.languages(); // Error: Method "languages" cannot be called after the SDK instance has been destroyed.
Properties
The SpeaqrSDK class contains several accessible properties that allow you to configure and obtain information about the SDK status.apiKey
Stores the api key used to authenticate requests to the Speaqr api.Access
get apiKey(): string;
set apiKey(apiKey: string);
Example
// Get the current API key
console.log("Current API key:", sdk.apiKey);
// Set a new API key
sdk.apiKey = "NEW_API_KEY";
logs
Indicates whether SDK logs are enabled in the console.Access
get logs(): boolean;
set logs(show: boolean);
Example
// Enable logs
sdk.logs = true;
// Check if logs are enabled
console.log("Logs enabled:", sdk.logs);
socketOpened
Indicates whether the socket connection is open.Access
get socketOpened(): boolean;
Example
// Check if the socket connection is open
if (sdk.socketOpened) {
console.log("Socket is currently open.");
} else {
console.log("Socket is closed.");
}
Methods
The SDK provides several methods to interact with the Speaqr api in batch. Their uses and configurations are detailed below.languajes
Gets the list of languages supported by the SDK for transcription, translation and speech synthesis.Syntax
languages(): Promise<{ id: string; name: string }[]>;
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
// Fetch the list of supported languages
sdk.languages()
.then((languages) => {
console.log("Supported languages:", languages);
})
.catch((error) => {
console.error("Error fetching languages:", error);
});
Reply
This method returns a promise that resolves to an array of objects, where each object represents a supported language. The id of the language will be returned in ISO3, and the name of the language, in the represented language itself.
availableVoices
Gets the list of available voices for speech synthesis (TTS) in a language and for an engine. Optionally you can filter the result by voice genre and/or voice engine.By this means it is possible to know if a language, voice and motor configuration can be realized, since voices are not available for all combinations.Syntax
availableVoices(params: {
language: string;
ttsEngine: 'block' | 'streaming';
voiceGender?: 'N' | 'F' | 'M';
voiceEngine?: 'standard' | 'neural' | 'generative';
}): Promise<{ ssmlGender: string; name: string; type: string }[]>;
Parameters
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
// Fetch the list of available voices for English (UK) with a streaming engine
sdk.availableVoices({
language: "en-gb",
ttsEngine: "streaming"
})
.then((voices) => {
console.log("Available voices:", voices);
})
.catch((error) => {
console.error("Error fetching available voices:", error);
});
Reply
processFile
Processes a Blob containing an audio waveform and performs the operation specified inmode
. The result will depend on the selected mode and will be returned in a promise.Syntax
processFile(params: {
mode?: 'sts' | 'stt' | 'stt+translation';
languageIdTarget?: string;
voiceGender?: 'N' | 'F' | 'M';
file: Blob;
}): Promise<{
transcription: string
languageIdSource: string
translation?: string
languageIdTarget?: string
file?: {
type: string
data: ArrayBuffer
}
}>;
Parameters
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
// Process an audio file with speech-to-text and translation
sdk.processFile({
mode: "stt+translation",
file: audioBlob,
languageIdTarget: "en-us"
})
.then((result) => {
console.log("Processing result:", result);
})
.catch((error) => {
console.error("Error processing file:", error);
});
Reply
The result of processFile
will depend on the mode
used. A response with mode=sts
would carry all the fields. The file.data
field is an ArrayBuffer
in mp3 format.
Communication with sockets
The Speaqr SDK enables real-time communication via sockets. These methods allow sending and receiving audio and text data without waiting for a blocking response, improving latency and optimizing interaction with the api.Flow of use
The use of sockets in the SDK follows the following flow:- Initialize the session configuration with
socketsInstance
. - Configure listening for responses with
socketsAddListener
. - Open the connection with
socketsOpen
. - Send data via
socketSendText
orsocketsSendStream
. - Close the connection when it is no longer needed with
socketsClose
.
Socket.IO handling
The Speaqr SDK uses Socket.IO for real-time communication. To ensure compatibility in all environments, in casesocket.io-client
is not present, it automatically handles its load as follows:Environment detection
Before initializing a socket connection (by callingsocketsInstance
), the SDK checks the environment in which it is running:- If you are in a browser, try loading
socket.io-client
from a CDN. - If you are in Node.js, try importing
socket.io-client
from the installed modules(require("socket.io-client")
). - If it cannot load
socket.io-client
, it throws an error indicating that it must be installed manually.
#loadSocketIO() {
return new Promise((resolve, reject) => {
//We check if we are in a browser
if (
typeof document !== 'undefined' &&
typeof document.nodeType !== 'undefined' &&
typeof window !== 'undefined' &&
window.document === document &&
document.nodeType === 9
){
//Browser
this.#loadSocketIOBrowser()
.then( resolve )
.catch( reject );
}else{
//We check if we are in Node
if (
typeof process !== 'undefined' &&
typeof process.versions !== 'undefined' &&
typeof process.versions.node !== 'undefined'
){
this.#loadSocketIONode()
.then( resolve )
.catch( reject );
}else{
reject('Socket IO cannot be loaded dynamically. You must instantiate it in your project.');
}
}
});
}
Dynamic loading in browsers
If the SDK detects that it is in a browser andio
is not defined, it loads socket.io-client
from the Socket.IO CDN. If socket.io-client
is already available in the browser, the SDK does not reload it. The SDK function that handles the loading is:
// static #SOCKETIO_SRC = 'https://cdn.socket.io/4.8.1/socket.io.min.js';
// static #SOCKETIO_INTEGRITY = 'sha384-mkQ3/7FUtcGyoppY6bz/PORYoGqOl7/aSUMn2ymDOJcapfS6PHqxhRTMh1RR0Q6+';
#loadSocketIOBrowser() {
return new Promise((resolve, reject) => {
if (typeof io!='undefined'){ //If it is already present we do not load it
resolve();
return;
}
const script = document.createElement('script');
script.src = SpeaqrSDK.#SOCKETIO_SRC;
script.integrity = SpeaqrSDK.#SOCKETIO_INTEGRITY;
script.crossOrigin = 'anonymous';
// When the script is loaded successfully
script.onload = () => resolve();
// En caso de error durante la carga
script.onerror = () => reject(new Error(`Failed to load script ${script.src}`));
// We add the script to the document
document.head.appendChild(script);
});
}
Dynamic loading in Node.js
If the SDK detects that you are in a Node.js environment andglobalThis.io
is not defined, it tries to import socket.io-client
directly. If it cannot import it will throw an error indicating that it must be installed manually. The function that takes care of the import is:
#loadSocketIONode() {
return new Promise((resolve, reject) => {
if (typeof globalThis.io !== 'undefined') {
resolve();
return;
}
try {
const { io } = require('socket.io-client');
globalThis.io = io;
resolve();
} catch (error) {
reject(new Error(`Failed to load socket.io-client on Node. Please install with "npm install socket.io-client". Error: ${error}`));
}
});
}
To avoid problems
If you work in Node.js, manually installsocket.io-client
. This will prevent the SDK from crashing if it tries to import it and can't find it.
npm install socket.io-client
If you are working in a browser with network restrictions (firewalls, CSP), make sure that your environment allows loading scripts from https://cdn.socket.io/.
If not, install socket.io-client
manually in your project and load it before initializing the SDK.socketsInstance
Configures an instance of sockets for real-time communication with the API. This method must be called before opening the connection withsocketsOpen()
. Returns a promise that is resolved when Socket.io
has been instantiated.Syntax
socketsInstance(params: {
languageIdSource?: string;
languageIdTarget?: string;
mode: "stt" | "tts" | "translator" | "sts";
sendType?: {
type: "buffer" | "streaming";
codec?: "mp3" | "linear16" | "mulaw" | "flac" | "opus" | "speex" | "g729" | "amr-nb" | "amr-wb";
samplerate?: number;
};
receiveType?: {
type: "buffer" | "streaming";
codec?: "mp3" | "linear16" | "mulaw";
samplerate?: number;
};
voiceGender?: "M" | "F" | "N";
voiceEngine?: "standard" | "neural" | "generative";
sttMode?: "continuous" | "phrase";
ttsEngine?: "block" | "streaming";
}): Promise;
Parameters
Example
Configure a real-time speech-to-speech
socket session.
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
// Configure a real-time socket session for speech-to-speech
sdk.socketsInstance({
mode: "sts",
languageIdSource: "en-us",
languageIdTarget: "es-es",
sendType: {
type: "buffer"
},
receiveType: {
type: "buffer",
codec: "mp3",
samplerate: 16000
},
voiceGender: "F",
voiceEngine: "generative",
sttMode: "continuous",
ttsEngine: "block"
});
Set up a real-time socket session to transcribe audio.
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
// Setting up a real-time socket session to transcribe audio
sdk.socketsInstance({
mode: "stt",
languageIdSource: "en-us",
sendType: {
type: "buffer"
},
sttMode: "continuous",
});
Set up a real-time socket session to synthesize audio from text.
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
// Set up a real-time socket session to synthesize audio from text.
sdk.socketsInstance({
mode: "tts",
languageIdSource: "en-us",
receiveType: {
type: "buffer"
},
voiceGender: "F",
voiceEngine: "generative",
ttsEngine: "block"
});
Set up a real-time socket session for translation.
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
// Configure a real-time socket session for translation
sdk.socketsInstance({
mode: "translator",
languageIdSource: "en-us",
languageIdTarget: "es-es"
});
socketsOpen
Opens the sockets connection previously configured withsocketsInstance()
. Failure to call socketsInstance
will result in an error. This method returns a promise that is resolved with an object containing information about the connection status. If the connection is already open it will resolve the promise with the status object that was received the first time it was opened.Syntax
socketsOpen(): Promise<{
success: boolean;
code: string;
mode: "stt" | "tts" | "translator" | "sts";
languageIdSource: string;
languageIdTarget?: string;
sendType?: {
type: "buffer" | "streaming";
codec?: 'mp3' | 'mulaw' | 'linear16' | 'flac' | 'opus' | 'speex' | 'g729' | 'amr-nb' | 'amr-wb';
samplerate?: number;
};
receiveType?: {
type: "buffer" | "streaming";
codec?: "mp3" | "linear16" | "mulaw";
samplerate?: number;
};
urlStreaming: string | null;
}>;
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
sdk.socketsInstance({
languageIdSource:'en-gb',
languageIdTarget:'fr-fr',
mode:'sts',
sendType:{type: 'buffer'},
receiveType:{type: 'buffer', codec: 'mp3', samplerate: 16000},
})
.then( () => {
//We establish the connection with the sockets
sdk.socketsOpen()
.then( (status) => {
//Open sockets
console.log(status);
})
.catch( (err) => {
console.error('An error occurred while connecting to the sockets.', err);
});
})
.catch( (err) => {
console.error('An error occurred while instantiating to the sockets.', err);
});
Reply
The status object always contains the success
field which will indicate if the connection was successful or not, and the code
field with an error or success code. The urlStreaming
field will contain the url to listen to the streaming audio in case receiveType.type
is set to streaming
. The rest of the fields are the ones configured in the call to socketsInstance
.
socketsClose
Returns a promise that is resolved when the socket connection established withsocketsOpen
is closed. If socketsInstance
has not been called an error will be returned. If socketsOpen
has not been called this method performs no action and will resolve the promise anyway.Syntax
socketsClose(): Promise;
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
sdk.socketsInstance({
languageIdSource:'en-gb',
languageIdTarget:'fr-fr',
mode:'sts',
sendType:{type: 'buffer'},
receiveType:{type: 'buffer', codec: 'mp3', samplerate: 16000},
})
.then( () => {
//We establish the connection with the sockets
sdk.socketsOpen()
.then( (status) => {
// Open sockets
console.log(status);
// We close the sockets
sdk.socketsClose()
.then( () => {
console.log('sockets are closed');
})
.catch( (err) => {
console.error('There was an error closing the sockets.', err);
});
})
.catch( (err) => {
console.error('An error occurred while connecting to the sockets.', err);
});
})
.catch( (err) => {
console.error('An error occurred while instantiating to the sockets.', err);
});
socketsAddListener
It subscribes a listener to a specific event of the socket connection. This allows to receive data in real time. Failure to callsocketsInstance
will result in an error.Syntax
socketsAddListener(eventType: 'result' | 'error' | 'connect' | 'disconnect', listener: (data: any) => void): void;
Parameters
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
sdk.socketsInstance({
languageIdSource:'en-gb',
languageIdTarget:'fr-fr',
mode:'sts',
sendType:{type: 'buffer'},
receiveType:{type: 'buffer', codec: 'mp3', samplerate: 16000},
})
.then( () => {
// We subscribe to events
sdk.socketsAddListener('result', (data) => {
console.log(data);
});
sdk.socketsAddListener('error', (error) => {
console.error(error);
});
// We establish the connection with the sockets
sdk.socketsOpen()
.then( (status) => {
//Open sockets
console.log(status);
})
.catch( (err) => {
console.error('An error occurred while connecting to the sockets.', err);
});
})
.catch( (err) => {
console.error('An error occurred while instantiating to the sockets.', err);
});
Reply
Depending on the event, the response obtained will be different. Below are the details for each one of them.connect
This event does not return any data.status_con
The object received is the status of the connection. It always contains the success field that will indicate if the connection was successful or not, and the code field with an error or success code. The urlStreaming field will contain the url to listen to the streaming audio in case receiveType.type is set to streaming. The rest of the fields are the ones configured in the call to socketsInstance.
result
The fields of the object received will depend on how the sockets were instantiated with themode
parameter. Below is an object for mode=sts
containing all possible fields.
error
This event receives an object with different descriptions of errors that may occur, either due to programming errors in instantiating the modes of use, or in the data being processed.
disconnect
Receives a string with the reason for the disconnection. For example:"io client disconnect" or "transport close"
socketsRemoveListener
Removes a listener from a specific event and function previously subscribed to withsocketAddListener
. If the socketAddListener
had not been made to that type of event and/or that function, an error will be obtained. If socketsInstance
has not been called, an error will be returned.Syntax
socketsRemomveListener(eventType: 'result' | 'error' | 'connect' | 'disconnect', listener: (data: any) => void): void;
Parameters
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
sdk.socketsInstance({
languageIdSource:'en-gb',
languageIdTarget:'fr-fr',
mode:'sts',
sendType:{type: 'buffer'},
receiveType:{type: 'buffer', codec: 'mp3', samplerate: 16000},
})
.then( () => {
// We subscribe to events
sdk.socketsAddListener('result', evt_result);
sdk.socketsAddListener('status_con', (status) => {
console.log(status);
// Once the connection is established, I unsubscribe from "result"
sdk.socketsRemoveListener('result', evt_result);
});
// We establish the connection with the sockets
sdk.socketsOpen()
.then( (status) => {
//Open sockets
console.log(status);
})
.catch( (err) => {
console.error('An error occurred while connecting to the sockets.', err);
});
})
.catch( (err) => {
console.error('An error occurred while instantiating to the sockets.', err);
});
// Function for the "result" event
function evt_result(data){
console.log(data);
}
socketsSendText
Sends a text to be processed and returns a promise, which is resolved with the status of the sockets received. If the sockets are not open an error will occur.Syntax
socketsSendText(text: string): Promise<{
status: boolean;
error?: object;
}>;
Parameters
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
sdk.socketsInstance({
languageIdSource:'en-gb',
languageIdTarget:'fr-fr',
mode:'translator'
})
.then( () => {
// We subscribe to events. Here we will receive the translation
sdk.socketsAddListener('result', (data) => {
console.log(data);
});
// We establish the connection with the sockets
sdk.socketsOpen()
.then( (status) => {
//Open sockets
console.log(status);
//I send the text to process
sdk.socketsSendText('Hello, world. How are you today?')
.then( response => console.log('Send status', response))
.catch( respose => console.error('Send status', response));
})
.catch( (err) => {
console.error('An error occurred while connecting to the sockets.', err);
});
})
.catch( (err) => {
console.error('An error occurred while instantiating to the sockets.', err);
});
socketsSendStream
Sends an audio fragment for processing and returns a promise, which is resolved with the status of the received socket send. If the sockets are not open an error will occur.Syntax
socketsSendStream(data: ArrayBuffer | Blob): Promise<{
status: boolean;
error?: object;
}>;
Parameters
Example
const apiKey='cFVBACTRF6nPzqetBcA2bG'; //Your valid apiKey
sdk = await SpeaqrSDK.create({apiKey, showLogs:true});
sdk.socketsInstance({
languageIdSource:'es-es',
languageIdTarget:'fr-fr',
mode:'sts',
sendType:{type: 'buffer'}, //Codec and samplerate are auto-detected from audio headers
receiveType:{type: 'buffer', codec: 'mp3', samplerate: 16000},
voiceGender:'M',
sttMode:'phrase',
voiceEngine:'neural',
ttsEngine:'block'
})
.then( () => {
//We subscribe to events. Here we will receive the translation
sdk.socketsAddListener('result', result => console.log(result));
//We establish the connection with the sockets
sdk.socketsOpen()
.then( () => {
start();
console.log('Speak now!!!!');
})
.catch( (err) => {
console.error('An error occurred while connecting to the sockets.');
});
})
.catch( (err) => {
console.error('An error occurred while instantiating to the sockets.');
});
// Start capturing and processing microphone audio
const start = async () => {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = ondataavailable;
mediaRecorder.start(500);
})
.catch(error => {
console.error("Error starting recording:", error);
});
}
// Here you receive each audio fragment in a Blob
const ondataavailable = (event) => {
if (!sdk.socketOpened) return;
if (event.data && event.data.size > 0) {
const audioChunk = event.data;
sdk.socketsSendStream(audioChunk);
}
};
This webpage uses cookies
The cookies in this website are used to customise contents and analyse traffic.
You may find details on cookies in the Privacy Policy section