# Stream transcription (WebSocket)

> wss /api/v1/stt/ws/ transcribes live 16 kHz PCM audio and returns partial and final results with word timings. Audio format, messages, billing and close codes.

## Endpoint

`wss://moknah.io/api/v1/stt/ws/`

Send raw audio as it is captured and receive the text as it is recognized: partial results while the person is speaking, and a final result with word timings for each finished sentence.

Requirements: an API key whose allowed services include `stt_ws`, and enough credits for one minute of streaming.

## Authentication and parameters

Send `Authorization: Bearer YOUR_API_KEY` on the handshake, or pass the key as a query parameter when headers cannot be set (browsers).

| Query parameter | Required | Description |
| --- | --- | --- |
| `api_key` | only without the header | The API key. |
| `language` | no | Language and region, for example `ar-SA`, `ar-EG`, `en-US`. Default `ar-JO`. An unsupported value falls back to the default. |
| `hints` | no | Words or phrases that are likely to be spoken, separated by commas, to improve their recognition. |

## Audio format

Send binary frames of raw PCM only:

- Sample rate: 16,000 Hz
- Sample format: 16-bit signed integer, little-endian
- Channels: 1 (mono)
- Frame size: small frames, for example 100 ms (3,200 bytes). A frame larger than 256,000 bytes closes the connection with code `4009`.

Do not send MP3, M4A, or WAV files with their header. Compressed audio produces empty or wrong text.

## Messages you receive

JSON text frames.

| Event | Example |
| --- | --- |
| Connected | `{"status": "connected", "message": "Ready to stream audio. Send 16kHz PCM audio.", "language": "ar-JO"}` |
| Partial result | `{"type": "partial", "text": "مرحبا بك في منصة"}` |
| Final result | see below |
| Error | `{"error": "..."}` |

Final result:

```json
{
  "type": "final",
  "text": "مرحبا بك في منصة مكنة.",
  "words": [
    {"word": "مرحبا", "start_time_ms": 150, "duration_ms": 300},
    {"word": "بك", "start_time_ms": 460, "duration_ms": 200}
  ]
}
```

## Ending the stream

Send the JSON text frame `{"command": "stop"}`. The connection closes with code `1000` and the unused part of the last prepaid minute is returned.

## Billing

Streaming is billed per minute of connection time, with a prepaid meter:

1. On connect, the credits for one minute are taken.
2. Each time a prepaid minute is used up, the next minute is taken. If the balance cannot cover it, the stream ends with `{"error": "Insufficient credits to continue streaming."}` and close code `4002`.
3. On disconnect, the exact duration is calculated to the second and the unused credits are returned.

The current rate per minute is in [Pricing](../pricing/index.md).

## Close codes

| Code | Meaning |
| --- | --- |
| 1000 | Normal end of the stream. |
| 4001 | No API key was sent. |
| 4002 | Authentication failed (invalid or inactive key, no `stt_ws` access, IP not allowed), or not enough credits to start or continue. |
| 4009 | An audio frame was larger than 256,000 bytes. |
| 4290 | Another speech to text stream of this account is already open. |

## Example

```python
# pip install websockets pyaudio
import asyncio
import json
import pyaudio
import websockets

API_KEY = "YOUR_API_KEY"
URL = "wss://moknah.io/api/v1/stt/ws/?language=ar-SA"
CHUNK = 1600  # 100 ms of 16 kHz mono 16-bit audio


async def send_microphone(ws):
    audio = pyaudio.PyAudio()
    stream = audio.open(format=pyaudio.paInt16, channels=1, rate=16000,
                        input=True, frames_per_buffer=CHUNK)
    loop = asyncio.get_running_loop()
    try:
        while True:
            data = await loop.run_in_executor(None, stream.read, CHUNK, False)
            await ws.send(data)
    except asyncio.CancelledError:
        await ws.send(json.dumps({"command": "stop"}))
        raise
    finally:
        stream.stop_stream()
        stream.close()
        audio.terminate()


async def print_results(ws):
    async for message in ws:
        data = json.loads(message)
        if data.get("type") == "partial":
            print("...", data["text"])
        elif data.get("type") == "final":
            print("FINAL:", data["text"])
        elif data.get("error"):
            print("Error:", data["error"])


async def main():
    headers = {"Authorization": f"Bearer {API_KEY}"}
    async with websockets.connect(URL, additional_headers=headers) as ws:
        await asyncio.gather(send_microphone(ws), print_results(ws))


asyncio.run(main())
```

In a browser, capture the microphone at 16 kHz, convert the Float32 samples to Int16 and send the buffer:

```javascript
const ws = new WebSocket("wss://moknah.io/api/v1/stt/ws/?api_key=YOUR_API_KEY&language=ar-SA");
ws.binaryType = "arraybuffer";

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.type === "final") console.log("Final:", data.text);
};

ws.onopen = async () => {
  const media = await navigator.mediaDevices.getUserMedia({ audio: true });
  const context = new AudioContext({ sampleRate: 16000 });
  const source = context.createMediaStreamSource(media);
  const processor = context.createScriptProcessor(4096, 1, 1);
  processor.onaudioprocess = (e) => {
    if (ws.readyState !== WebSocket.OPEN) return;
    const input = e.inputBuffer.getChannelData(0);
    const pcm = new Int16Array(input.length);
    for (let i = 0; i < input.length; i++) {
      const s = Math.max(-1, Math.min(1, input[i]));
      pcm[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
    }
    ws.send(pcm.buffer);
  };
  source.connect(processor);
  processor.connect(context.destination);
};

function stop() {
  ws.send(JSON.stringify({ command: "stop" }));
}
```

A key placed in browser code is visible to every visitor. For production, open the stream from your server, or issue the key only to trusted clients.
