WebSocket ASR API

BHASHINI's WebSocket ASR endpoint enables low-latency, real-time speech-to-text streaming. Audio chunks captured from a microphone or media stream are continuously sent over a persistent Socket.IO / WebSocket connection, and partial or final transcriptions are returned asynchronously as the speaker speaks.

WSS wss://dhruva-api.bhashini.gov.in

Connection Lifecycle

PhaseEvent NameDirectionDescription
1Handshake
connectClient → ServerEstablishes the WebSocket connection with authentication query parameters or Authorization header.
2Task Initialization
startClient → ServerSends the ASR pipeline task configuration (language, service ID, sampling rate, response frequency).
3Server Ready
readyServer → ClientAcknowledges the session is initialized and ready to ingest raw streaming audio chunks.
4Audio Streaming
dataClient → ServerStreams consecutive PCM audio chunks (typically 100ms–250ms chunks at 16 kHz 16-bit mono).
5Live Transcription
responseServer → ClientEmits intermediate or final transcribed text snippets asynchronously as audio is processed.
6Teardown
disconnect / stopBidirectionalStops audio streaming gracefully and closes the WebSocket connection.

Audio Specifications

PropertyRecommendedSupported Range
Sampling Rate16,000 Hz (16 kHz)8,000 Hz or 16,000 Hz
Encoding / Bit Depth16-bit Linear PCMSigned 16-bit little-endian
Channels1 (Mono)Mono required
Chunk Duration100 ms – 200 ms3,200 bytes per chunk at 16 kHz
ContainerRaw PCM framesWAV (header skipped) or raw PCM

Client SDK Implementations

Select your programming language below for a complete, ready-to-run streaming client:

1. Install Dependencies

Terminal
npm install socket.io-client

2. Streaming Client Script

stream_asr.js
import { io } from "socket.io-client";
import fs from "fs";


const API_KEY = "YOUR_INFERENCE_API_KEY";
const SERVICE_ID = "ai4bharat/conformer-hi-gpu--t4";
const SERVER_URL = "wss://dhruva-api.bhashini.gov.in";


const socket = io(SERVER_URL, {
  transports: ["websocket"],
  extraHeaders: {
    Authorization: API_KEY,
  },
});


socket.on("connect", () => {
  console.log("[Connected] WebSocket connection established.");


  const taskConfig = {
    pipelineTasks: [
      {
        taskType: "asr",
        config: {
          language: { sourceLanguage: "hi" },
          serviceId: SERVICE_ID,
          audioFormat: "wav",
          samplingRate: 16000,
        },
      },
    ],
  };


  socket.emit("start", taskConfig);
});


socket.on("ready", () => {
  console.log("[Ready] Streaming audio chunks...");


  const stream = fs.createReadStream("input_16k_mono.wav", {
    highWaterMark: 3200, // 100ms chunks
    start: 44,          // skip WAV header
  });


  stream.on("data", (chunk) => {
    socket.emit("data", chunk);
  });


  stream.on("end", () => {
    console.log("[Completed] Audio stream reached end of file.");
    socket.emit("stop", true);
  });
});


socket.on("response", (data) => {
  const result = typeof data === "string" ? JSON.parse(data) : data;
  const text = result?.pipelineResponse?.[0]?.output?.[0]?.source;
  if (text) {
    console.log(`[Live Transcription]: ${text}`);
  }
});


socket.on("disconnect", () => {
  console.log("[Disconnected] Connection closed.");
});

Configuration Parameters

ParameterTypeRequiredDescription
taskTypestringRequiredMust be "asr".
serviceIdstringRequiredSpecific ASR model Service ID (e.g. ai4bharat/conformer-hi-gpu--t4).
language.sourceLanguagestringRequiredSource language ISO-639-1 code (e.g. "hi", "en", "ta").
samplingRateintegerOptionalAudio sampling rate in Hertz (16000 or 8000). Default: 16000.
audioFormatstringOptionalAudio container format, typically "wav" or raw PCM.
responseFrequencyInSecsnumberOptionalFrequency of intermediate response emissions in seconds (e.g. 1.0).

Troubleshooting & FAQs

  • Error 401 / Unauthorized on Connect: Ensure your inference API key is passed in extraHeaders: { "Authorization": "..." } or query parameters.
  • No Live Output Received: Verify that the microphone or audio stream is sending PCM data at the configured sample rate (16000 Hz or 8000 Hz).
  • High Latency / Lag: Keep audio chunk buffer size between 100ms and 250ms (3200 bytes per chunk at 16kHz 16-bit mono). Avoid sending overly small (e.g. 10ms) or overly large (e.g. >1000ms) packets.