Skip to content

SDKs and tools

JavaScript SDK

@shihab/asr for Node 18+ and browsers.

Install

Terminal
npm install @shihab/asr

# until the package is live on npm:
npm install https://voice.shihab.co.uk/sdk/shihab-asr-1.1.0.tgz

Node 18 or newer and modern browsers. ESM and CommonJS. TypeScript types included.

No build step? The browser build is a single ES module you can import straight from our download page:

index.html
<script type="module">
  import { startMicrophoneStream } from 'https://voice.shihab.co.uk/sdk/shihab-asr-browser-1.1.0.js';
  // ...
</script>

Create a client

typescript
import { ShihabASR } from '@shihab/asr';

const client = new ShihabASR({
  apiKey: process.env.SHIHAB_API_KEY, // the default in Node
  timeout: 120_000,                   // ms per request
  maxRetries: 2,                      // 429, 503 and connection errors
});

Transcribe a file

javascript
const result = await client.listen('call.m4a', { numerals: true, tags: ['support'] });
console.log(result.transcript);
for (const seg of result.segments) console.log(seg.start, seg.end, seg.text);
console.log(result.usage.cost_usd, result.request_id);

// Buffer, Uint8Array, Blob/File, Node or Web streams, or a URL
await client.listen(buffer, { filename: 'note.ogg' });
await client.listen({ url: 'https://example.com/recordings/call-1029.mp3' });

Responses are the API JSON exactly as documented (snake_case fields), fully typed.

Async jobs

javascript
const job = await client.transcriptions.create('meeting.mp3', {
  webhookUrl: 'https://example.com/hooks/shihab',
  metadata: { ticket: 1234 },
});
const done = await client.transcriptions.wait(job.id, { timeoutMs: 600_000 });
if (done.status === 'completed') console.log(done.transcript);

const page = await client.transcriptions.list({ limit: 20, status: 'completed' }); // { data, has_more, next_cursor }
await client.transcriptions.delete(job.id);

Streaming

javascript
const stream = client.stream({ encoding: 'linear16', sampleRate: 16000, interimResults: true });

stream.on('results', (e) => console.log(e.is_final ? 'final' : 'interim', e.transcript));
stream.on('utteranceEnd', (e) => console.log('ended at', e.last_word_end));
stream.on('error', (err) => console.error(err.code, err.message));

stream.send(pcmChunk);                 // queued until the socket opens
stream.finalize();                     // flush the current utterance
const finished = await stream.close(); // { audio_seconds, billed_seconds, cost_usd }

// or: for await (const event of stream) { ... }

Browser microphone

startMicrophoneStream from @shihab/asr/browser streams the microphone with a temporary token. Full walkthrough: Browser microphone streaming.

Text to speech

speak() resolves with the whole audio (Uint8Array); speakStream() resolves as soon as the audio starts and yields it chunk by chunk. See Text to speech.

import { writeFile } from 'node:fs/promises';
import { ShihabASR } from '@shihab/asr';

const client = new ShihabASR({ apiKey: process.env.SHIHAB_API_KEY });
const speech = await client.speak({ text: 'أهلا وسهلا، معك شهاب. كيف بقدر أساعدك اليوم؟', voice: 'ps-female', dialect: 'ps' });
await writeFile('hello.mp3', speech.audio);
console.log(speech.characters, speech.costUsd); // 44 "0.00132"

Webhook verification

Node.js
// npm install express @shihab/asr
import express from 'express';
import { verifyWebhook } from '@shihab/asr/webhooks';

const app = express();

app.post('/hooks/shihab', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = verifyWebhook(req.body, req.headers['shihab-signature'], process.env.SHIHAB_WEBHOOK_SECRET);
  } catch {
    return res.sendStatus(400); // WebhookVerificationError
  }
  if (event.type === 'transcription.completed') console.log(event.data.id, event.data.transcript);
  else console.log(event.data.id, 'failed:', event.data.error);
  res.sendStatus(204);
});

app.listen(3000);

Errors and retries

Errors are typed (APIError with status, type, code, message, param, requestId). 429 and 503 are retried with backoff automatically.

Node.js
import { APIError, BadRequestError, InsufficientCreditsError, RateLimitError, ShihabASR } from '@shihab/asr';

const client = new ShihabASR({ apiKey: process.env.SHIHAB_API_KEY }); // retries 429 and 503 automatically

try {
  const result = await client.listen('call.m4a');
} catch (err) {
  if (err instanceof InsufficientCreditsError) console.log('Out of credit: top up in the console');
  else if (err instanceof BadRequestError) console.log('Check the audio or parameters:', err.code, err.param);
  else if (err instanceof RateLimitError) console.log('Still rate limited; wait', err.retryAfter, 's');
  else if (err instanceof APIError) console.log(err.status, err.code, err.message, err.requestId);
  else throw err;
}

Need help? Email [email protected] or message us on WhatsApp.