> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gnani.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Phone audio

> Transcribe 8 kHz telephone audio: the sample rate to send, the telephony voice-activity settings for live calls, and how to handle µ-law.

Use this when your audio comes from phone calls: a telephone line, an IVR, a contact-centre platform or a SIP trunk, usually at 8 kHz.

## Turn it on

For live calls, connect to [Realtime streaming](https://docs.gnani.ai/api/STT/stt-websocket.md) with `x-sample-rate: 8000` and the telephony voice-activity settings. This example streams the 8 kHz sample clip in real time:

```python Python theme={null}
# pip install websockets
import asyncio
import json
import os
import wave

import websockets

HEADERS = {
    "x-api-key-id": os.environ["GNANI_API_KEY"],
    "model": "prisma-v3.0",
    "language_code": "hi-IN",
    "x-sample-rate": "8000",
    "x-vad-threshold": "0.7",
    "x-min-speech-ms": "200",
    "x-min-silence-ms": "500",
}
FRAME_SECONDS = 0.064  # one 1,024-byte frame is 64 ms at 8 kHz


async def send_audio(ws, path):
    with wave.open(path) as w:  # 16-bit mono PCM at 8 kHz
        pcm = w.readframes(w.getnframes())
    for i in range(0, len(pcm), 1024):
        await ws.send(pcm[i:i + 1024].ljust(1024, b"\0"))  # pad the last frame with silence
        await asyncio.sleep(FRAME_SECONDS)                 # send in real time
    await ws.send(json.dumps({"type": "commit"}))          # transcribe the last words now


async def print_messages(ws):
    async for message in ws:
        msg = json.loads(message)
        if msg["type"] == "transcript":
            print(msg["text"])
        elif msg["type"] == "error":
            print("error:", msg["message"])


async def main():
    async with websockets.connect(
        "wss://api.vachana.ai/stt/v3/stream",
        additional_headers=HEADERS,  # extra_headers on websockets < 13
    ) as ws:
        receiver = asyncio.create_task(print_messages(ws))
        await send_audio(ws, "phone.wav")
        await asyncio.sleep(2)  # let the last transcript arrive
        receiver.cancel()


asyncio.run(main())
```

```javascript Node.js theme={null}
// npm install ws
import { readFileSync } from "node:fs";
import WebSocket from "ws";

const FRAME_MS = 64; // one 1,024-byte frame is 64 ms at 8 kHz
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const ws = new WebSocket("wss://api.vachana.ai/stt/v3/stream", {
  headers: {
    "x-api-key-id": process.env.GNANI_API_KEY,
    "model": "prisma-v3.0",
    "language_code": "hi-IN",
    "x-sample-rate": "8000",
    "x-vad-threshold": "0.7",
    "x-min-speech-ms": "200",
    "x-min-silence-ms": "500",
  },
});

async function sendAudio(path) {
  const pcm = readFileSync(path).subarray(44); // skip the 44-byte WAV header of the sample clip
  for (let offset = 0; offset < pcm.length; offset += 1024) {
    const frame = Buffer.alloc(1024); // the last frame is padded with silence
    pcm.copy(frame, 0, offset, offset + 1024);
    ws.send(frame);
    await sleep(FRAME_MS); // send in real time
  }
  ws.send(JSON.stringify({ type: "commit" })); // transcribe the last words now
}

ws.on("open", async () => {
  await sendAudio("phone.wav");
  await sleep(2000); // let the last transcript arrive
  ws.close();
});

ws.on("message", (data, isBinary) => {
  if (isBinary) return;
  const msg = JSON.parse(data);
  if (msg.type === "transcript") console.log(msg.text);
  else if (msg.type === "error") console.error("error:", msg.message);
});
ws.on("error", (error) => console.error(error));
```

```python Python SDK theme={null}
import asyncio
import io
import os
import wave

from gnani.stt import GnaniSTTStreamClient


async def main():
    with wave.open("phone.wav") as w:  # 16-bit mono PCM at 8 kHz
        pcm = io.BytesIO(w.readframes(w.getnframes()))
    async with GnaniSTTStreamClient(
        api_key=os.environ["GNANI_API_KEY"],
        model="prisma-v3.0",
        language_code="hi-IN",
        sample_rate=8000,
        vad_threshold=0.7,
        min_speech_ms=200,
        min_silence_ms=500,
    ) as stream:
        await stream.stream_audio(pcm, on_transcript=lambda t: print(t.text))


asyncio.run(main())
```

Download the sample first: `curl -o phone.wav https://docs.gnani.ai/audio/samples/phone-8k-hi-IN.wav`. For recorded calls, send the file as it is to [REST](https://docs.gnani.ai/api/STT/speech-to-text.md) (up to 30 seconds) or [Batch](https://docs.gnani.ai/api/STTBatch/Introduction.md); no sample-rate setting is needed there.

## Examples

The same sentence twice: once at 16 kHz, and once made directly as 8 kHz G.711 µ-law, the usual telephone encoding, then decoded to 16-bit PCM (synthetic, Timbre v3.0).

| Clip | Listen |
| - | - |
| 16 kHz | <audio controls preload="none" src="https://docs.gnani.ai/audio/samples/names-and-terms-hi-IN.wav" aria-label="Sample clip at 16 kHz, in Hindi" /> |
| 8 kHz (phone) | <audio controls preload="none" src="https://docs.gnani.ai/audio/samples/phone-8k-hi-IN.wav" aria-label="Sample clip at 8 kHz, phone quality, in Hindi" /> |

What is said: नमस्ते, मैं Inya से प्रियंवदा बोल रही हूँ। आपका NACH mandate कल Vachana पर रिन्यू हो जाएगा।

On REST with `language_code=hi-IN`:

| Clip | Model | Options | Transcript |
| - | - | - | - |
| 16 kHz | Prisma v3.0 | — | नमस्ते, मैं India से प्रियम्वदा बोल रही हूँ, आपका NACH mandate कल वचना पर renew हो जाएगा। |
| 8 kHz | Prisma v3.0 | — | नमस्ते, मैं India से प्रियंवदा बोल रही हूँ। आपका NACH mandate कल वचना पर renew हो जाएगा। |
| 8 kHz | Prisma v3.0 | `keyterms` | नमस्ते, मैं **Inya** से प्रियंवदा बोल रही हूँ, आपका NACH mandate कल **Vachana** पर रिन्यू हो जाएगा। |
| 16 kHz | Prisma v2.5 | — | नमस्ते, मैं इंडिया से प्रियंवदा बोल रही हूँ, आपका एन ए सी एच मैंडेट कल वाचना पर रिन्यू हो जाएगा। |
| 8 kHz | Prisma v2.5 | — | नमस्ते, मैं इंडिया से प्रियंवदा बोल रही हूँ, आपका एन ए सी एच मैंडेट कल वचना पर रिन्यू हो जाएगा। |

At 8 kHz both models kept the sentence; the hardest word, the product name *Vachana*, is where they differed. In two more runs of the 8 kHz audio, Prisma v3.0 wrote it as *1 January*: once as a Batch job with the same WAV, and once on REST with the audio left as a µ-law WAV. With `keyterms` (`["Inya","प्रियंवदा","NACH mandate","Vachana"]`) every name came out right. Each REST request gave the same result both times it was run.

## By interface

> [tab] Realtime
>
> Send raw 16-bit mono PCM in 1,024-byte frames, one every 64 ms at 8 kHz, with `x-sample-rate: 8000`. The rate must match your audio. Use the telephony voice-activity settings ([presets](https://docs.gnani.ai/api/STT/stt-websocket.md#presets)):
>
> | Header | Telephony | Why |
> | - | - | - |
> | `x-vad-threshold` | `0.65` to `0.75` | Line noise should not count as speech |
> | `x-min-speech-ms` | `200` (the default at 8 kHz) | Short clicks should not open a segment |
> | `x-min-silence-ms` | `400` to `600` | Ends a turn without cutting a speaker off mid-sentence |
>
> For IVR menus and short commands, a shorter `x-min-silence-ms` (around `300`) returns each answer sooner.

> [tab] REST
>
> Upload the recording as it is, at its own sample rate: WAV, MP3, OGG, FLAC, AAC or M4A, up to 30 seconds. There is no sample-rate field.

> [tab] Batch
>
> Upload or link the recordings as they are, up to 4 hours each. Batch also accepts `.amr`, a common mobile and voicemail format. For stereo call recordings with one party per channel, see `is_multi_channel` in [Configuration](https://docs.gnani.ai/api/STTBatch/Introduction.md#configuration).

## By model

Both models take 8 kHz audio on every interface, and the telephony settings are the same for both. In the example, Prisma v2.5 spelled out *NACH* as letters at both sample rates, while Prisma v3.0 kept it as *NACH mandate*. On Prisma v3.0, `keyterms` helps most with phone audio; on Prisma v2.5, use [word boosting](https://docs.gnani.ai/api/STT/names-and-terms.md#by-model).

## Rules and limits

| | Rule |
| - | - |
| `x-sample-rate` (Realtime) | `8000`, `16000`, `44100` or `48000`. Default `16000`. Must match the audio. |
| Audio on Realtime | Raw 16-bit little-endian mono PCM, no header, 1,024-byte frames at real-time pace |
| `x-min-speech-ms` default | `200` at 8 kHz, `100` otherwise |
| Session length (Realtime) | Up to 15 minutes; idle timeout 60 seconds by default (`x-idle-timeout-sec`, 5 to 900) |
| REST | Up to 30 seconds per file |
| Batch | Up to 4 hours per file |

## Things to watch for

* **A wrong `x-sample-rate` garbles the transcript.** 8 kHz audio sent as `16000` plays at double speed to the model. Read the rate from your telephony platform, not from a default.
* **Decode µ-law and A-law before streaming.** Phone systems often deliver G.711 µ-law or A-law, but Realtime takes only 16-bit PCM. In Python, `audioop.ulaw2lin(data, 2)` does it (on Python 3.13 and later, install the `audioop-lts` package). For files sent to REST or Batch, prefer 16-bit PCM WAV: µ-law WAV is not a documented format, even though REST accepted one in testing.
* **Rare words suffer first on phone audio.** Names, brands and codes are the most likely to change, as *Vachana* did in the example. Use [keyterms or word boosting](https://docs.gnani.ai/api/STT/names-and-terms.md).
* **One speaker per channel.** If your platform records the caller and the agent on separate channels, stream each channel on its own Realtime connection rather than mixing them. On Batch, see `is_multi_channel` in [Configuration](https://docs.gnani.ai/api/STTBatch/Introduction.md#configuration).
* **Send frames at real-time pace.** Sending a recording faster than real time makes voice-activity detection less accurate.
* **Python SDK:** the stream client's options are `sample_rate`, `vad_threshold`, `min_speech_ms` and `min_silence_ms`.

## Related

> [card] [Voice activity detection](https://docs.gnani.ai/api/STT/stt-websocket.md#voice-activity-detection-vad-tuning)
>
> Every VAD header, its range, and when to change it.

> [card] [Improve names and terms](https://docs.gnani.ai/api/STT/names-and-terms.md)
>
> Keep names and codes right on noisy, narrowband audio.

> [card] [Label speakers](https://docs.gnani.ai/api/STT/label-speakers.md)
>
> Who said what in recorded calls.

> [card] [Phone audio from Text-to-Speech](https://docs.gnani.ai/api/TTS/tts-inference.md#audio-format-reference)
>
> µ-law and A-law output for the other side of the call.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.