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

# Streaming audio watermark detection

> Detect the Telnyx text-to-speech watermark in a live audio stream over a WebSocket. Endpoint, authentication, query parameters, messages, session limits, and Python and Node.js examples.

Stream raw audio over a WebSocket and receive a `detection` message as soon as the Telnyx text-to-speech watermark reads on a channel. Use it for audio that is still coming in, such as a live call. For a recorded file, use the [HTTP endpoint](https://developers.telnyx.com/docs/voice/watermark-detection.md#quickstart) instead.

## Endpoint

```
wss://api.telnyx.com/v2/audio_watermark_detections/stream
```

## Authentication

Send your API key in the `Authorization` header of the WebSocket upgrade request:

```
Authorization: Bearer YOUR_API_KEY
```

Browsers cannot set headers on a WebSocket. Send the key as two subprotocols instead: the `telnyx-auth-ws` marker, then `base64url.bearer.telnyx.` followed by the key in base64url without padding. Send either the header or the subprotocols, not both.

```javascript theme={null}
const encoded = btoa(apiKey).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const ws = new WebSocket(
  "wss://api.telnyx.com/v2/audio_watermark_detections/stream?format=mulaw&sample_rate=8000",
  ["telnyx-auth-ws", `base64url.bearer.telnyx.${encoded}`],
);
ws.binaryType = "arraybuffer";
```

Do not ship your API key to browsers you do not control. For public web apps, proxy the stream through your server.

The upgrade request fails before the WebSocket opens with HTTP `401` for missing or invalid credentials, `403` for an account level that does not permit watermark detection, and `422` (`37005`) for an organization whose data locality this endpoint does not serve.

## Query parameters

Set all options as query parameters on the upgrade request. You cannot change them during the session.

| Parameter | Type | Default | Description |
| - | - | - | - |
| `sample_rate` | integer | None, required | Sample rate of the audio in Hz. Any integer from `8000` to `48000`. |
| `format` | string | `l16` | Audio encoding. `l16` is 16-bit signed PCM, little-endian. `mulaw` and `alaw` are G.711, one byte per sample. |
| `channels` | integer | `1` | Number of interleaved channels: `1` or `2`. |

A missing or unsupported value opens the connection, sends an `invalid_params` error frame, and closes it with code `1008`.

Stream the two legs of a call as two channels rather than a mono mix: each channel is read on its own, and the other party's voice masks the watermark in a mix.

## Session flow

1. Open the WebSocket with the query parameters.
2. Send audio as **binary** frames: raw samples, `channels` interleaved, with no header. Each frame must contain a whole number of samples for all channels and must not exceed 65,536 bytes. 20 ms frames are a good default; at 8 kHz `mulaw`, 20 ms of one channel is 160 bytes.
3. Read messages while you send. When the watermark reads on a channel, the server sends a `detection` message for it.
4. When you have no more audio, send the text frame `{"type": "end_of_stream"}`.
5. The server sends a `summary` message, then closes with code `1000`.

```
Client → Server  binary: 320 bytes (20 ms, l16, 8 kHz, mono)
Client → Server  binary: 320 bytes
...
Client ← Server  text:   {"type":"detection","channel":0,"watermark_detected":true,"detected_at_millis":4000}
...
Client → Server  text:   {"type":"end_of_stream"}
Client ← Server  text:   {"type":"summary","data":{...}}
Client ← Server  close:  1000 end_of_stream
```

You can send audio faster than real time, for example to check a file over the WebSocket.

## Messages

### Detection

Sent once for each channel whose watermark reads, as soon as it reads. Channels without a watermark send none.

```json theme={null}
{
  "type": "detection",
  "channel": 0,
  "watermark_detected": true,
  "detected_at_millis": 4000
}
```

`detected_at_millis` is the position in the channel's audio at which the watermark read. Each channel is first read after 4 seconds of its audio, then about every 2 seconds, and less often after 30 seconds. Clean text-to-speech audio can read at the first read; through phone networks, expect 8 to 20 seconds of synthesized speech.

After a detection, that channel is no longer read. You can end the stream as soon as you have the answer you need.

### Summary

Sent once after `end_of_stream`, or at a [session limit](#session-limits). `data` is the same object that the [HTTP endpoint](https://developers.telnyx.com/docs/voice/watermark-detection.md#reading-the-result) returns, with `audio.format` set to the stream's `format`.

```json theme={null}
{
  "type": "summary",
  "data": {
    "record_type": "audio_watermark_detection",
    "id": "d2c9f588-1e3b-4a47-9c2d-7b8e6f5a4c31",
    "watermark_detected": true,
    "confidence": "high",
    "channels": [{ "channel": 0, "watermark_detected": true }],
    "audio": { "duration_millis": 24060, "sample_rate": 8000, "format": "mulaw", "channels": 1 },
    "created_at": "2026-12-04T14:26:52.318Z"
  }
}
```

If you close the connection without `end_of_stream`, you get no summary.

### Error

```json theme={null}
{
  "type": "error",
  "code": "invalid_params",
  "message": "sample_rate is required: the audio's rate in Hz, 8000-48000"
}
```

`code` is a stable identifier; `message` is for humans, do not parse it. Some errors end the session and some only drop a frame. See [WebSocket errors](https://developers.telnyx.com/docs/voice/watermark-detection/errors.md#websocket-errors).

## Session limits

A session is limited to 590 seconds, and to 60 minutes of audio. At either limit, the server sends the `summary` for the audio received so far, then a `max_session_duration` error frame, and closes with `1008`. To keep checking a longer stream, open a new session.

## Examples

Both examples read a 16-bit PCM WAV file, stream it in 20 ms frames in real time as a live source would, and print each detection and the summary. Because they stream in real time, a file longer than about 9.5 minutes reaches the [session limit](#session-limits); remove the 20 ms pause to send faster than real time. Save the Node.js example as `detect-stream.mjs`. To convert a file with `ffmpeg`:

```bash theme={null}
ffmpeg -i input.mp3 -c:a pcm_s16le call-recording.wav
```

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

import websockets

API_KEY = os.environ["TELNYX_API_KEY"]
INPUT_FILE = "call-recording.wav"  # 16-bit PCM WAV, 1 or 2 channels, 8-48 kHz
URL = "wss://api.telnyx.com/v2/audio_watermark_detections/stream"


async def send_audio(ws, wav):
    """Send 20 ms frames in real time, as a live stream would, then end the stream."""
    frames_per_chunk = wav.getframerate() // 50
    while chunk := wav.readframes(frames_per_chunk):
        await ws.send(chunk)
        await asyncio.sleep(0.02)
    await ws.send(json.dumps({"type": "end_of_stream"}))


async def main():
    with wave.open(INPUT_FILE, "rb") as wav:
        if wav.getsampwidth() != 2:
            raise SystemExit("Convert the file to 16-bit PCM first")
        query = f"?format=l16&sample_rate={wav.getframerate()}&channels={wav.getnchannels()}"
        async with websockets.connect(
            URL + query, additional_headers={"Authorization": f"Bearer {API_KEY}"}
        ) as ws:
            sender = asyncio.create_task(send_audio(ws, wav))
            try:
                async for message in ws:
                    event = json.loads(message)
                    if event["type"] == "detection":
                        print(f"Watermark on channel {event['channel']} "
                              f"after {event['detected_at_millis'] / 1000:.1f} s of audio")
                    elif event["type"] == "summary":
                        data = event["data"]
                        print("Summary:", data["watermark_detected"], data["confidence"])
                    elif event["type"] == "error":
                        print("Error:", event["code"], event["message"])
            except websockets.ConnectionClosedError:
                pass  # closed with an error code; see ws.close_code below
            finally:
                sender.cancel()
            print("Closed:", ws.close_code, ws.close_reason)


asyncio.run(main())
```

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

const API_KEY = process.env.TELNYX_API_KEY;
const INPUT_FILE = "call-recording.wav"; // 16-bit PCM WAV, 1 or 2 channels, 8-48 kHz
const URL = "wss://api.telnyx.com/v2/audio_watermark_detections/stream";

// Find the format and data chunks of a WAV file.
function readWav(path) {
  const buf = fs.readFileSync(path);
  let offset = 12;
  let fmt;
  while (offset + 8 <= buf.length) {
    const id = buf.toString("ascii", offset, offset + 4);
    const size = buf.readUInt32LE(offset + 4);
    const body = offset + 8;
    if (id === "fmt ") {
      fmt = {
        channels: buf.readUInt16LE(body + 2),
        sampleRate: buf.readUInt32LE(body + 4),
        bitsPerSample: buf.readUInt16LE(body + 14),
      };
    } else if (id === "data") {
      return { ...fmt, pcm: buf.subarray(body, body + size) };
    }
    offset = body + size + (size % 2);
  }
  throw new Error("No data chunk in the WAV file");
}

const wav = readWav(INPUT_FILE);
if (wav.bitsPerSample !== 16) throw new Error("Convert the file to 16-bit PCM first");

const query = `?format=l16&sample_rate=${wav.sampleRate}&channels=${wav.channels}`;
const ws = new WebSocket(URL + query, {
  headers: { Authorization: `Bearer ${API_KEY}` },
});

ws.on("open", async () => {
  // Send 20 ms frames in real time, as a live stream would, then end the stream.
  const chunkBytes = Math.floor(wav.sampleRate / 50) * wav.channels * 2;
  for (let i = 0; i < wav.pcm.length && ws.readyState === WebSocket.OPEN; i += chunkBytes) {
    ws.send(wav.pcm.subarray(i, i + chunkBytes));
    await new Promise((resolve) => setTimeout(resolve, 20));
  }
  if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "end_of_stream" }));
});

ws.on("message", (message, isBinary) => {
  if (isBinary) return;
  const event = JSON.parse(message.toString());
  if (event.type === "detection") {
    console.log(`Watermark on channel ${event.channel} after ${event.detected_at_millis / 1000} s of audio`);
  } else if (event.type === "summary") {
    console.log("Summary:", event.data.watermark_detected, event.data.confidence);
  } else if (event.type === "error") {
    console.log("Error:", event.code, event.message);
  }
});

ws.on("unexpected-response", (req, res) => {
  console.error("Handshake failed with HTTP", res.statusCode);
});

ws.on("error", (err) => console.error("WebSocket error:", err.message));

ws.on("close", (code, reason) => console.log("Closed:", code, reason.toString()));
```

Output for a two-channel call recording with Telnyx text-to-speech on the second channel:

```
Watermark on channel 1 after 10.8 s of audio
Summary: True high
Closed: 1000 end_of_stream
```

On close `1011` or `1013`, or a close without a summary, the failure is temporary: reconnect with exponential backoff and send the audio again. See [Close codes](https://developers.telnyx.com/docs/voice/watermark-detection/errors.md#close-codes).

The [WebSocket API reference](https://developers.telnyx.com/api-reference/websockets/detect-the-telnyx-tts-watermark-over-websocket.md) lists every message schema.
