# Bring your own bot over media streams

> Run your own speech pipeline on MoreVoice's phone lines: a WebSocket bot that hears the caller, answers with audio, handles barge-in, and hands the call to a person. MoreVoice keeps the numbers, routing, recording and compliance.

You have a voice bot already: your recogniser, your model, your voice. MoreVoice gives it phone lines. With a [media stream](https://docs.morevoice.ai/guides/media-streams/) in `connect` mode, MoreVoice answers the call, runs your IVR and routing, records it, applies the compliance rules, and streams the caller's audio to your WebSocket server; your bot sends audio back, and can transfer the call to your agents or end it.

## How it works

| Your bot gets | Your bot sends |
| --- | --- |
| `start`: the call's IDs, the audio format and your custom parameters | `media`: audio to play |
| `media`: 20 ms of the caller's audio at a time | `mark`: "tell me when the caller has heard this far" |
| `mark`: playback reached one of your marks | `clear`: stop playing now (the caller interrupted) |
| `dtmf`: a key the caller pressed | `transfer`, `hangup`, `metadata`: MoreVoice's own additions |
| `stop`: the stream is over | |

The protocol is compatible with Twilio Media Streams; the [protocol reference](https://docs.morevoice.ai/guides/media-streams/#the-protocol) has every field. The SDK's `mediaStream` helpers verify the connection, decode μ-law or PCM to 16-bit samples at the rate you ask for, and encode what you send back.

## Build it

1. **Your pipeline.** The bot only needs four things from it: hear audio, decide a reply when the caller pauses, synthesise speech, close. Put your vendors behind this interface. `DemoPipeline` answers with tones, so you can run everything before you wire in a single API key.

   ```ts title="pipeline.ts"
   // Your speech pipeline: recognition, the bot and speech synthesis. Plug in your own vendors here: the bot in bot.ts
   // only needs these four methods. DemoPipeline answers every utterance with a short tone, so the recipe runs without
   // any vendor account.
   export interface Reply {
   	text: string;
   	/** After speaking: hand the call to a person, or end it. */
   	then?: "transfer" | "hangup";
   }

   export interface Pipeline {
   	/** The caller's audio, 16 kHz PCM, as it arrives (stream it to your speech recogniser). */
   	listen(pcm: Int16Array): void;
   	/** The caller stopped talking: what does the bot say? Null to stay quiet. */
   	reply(): Promise<Reply | null>;
   	/** Speech for a reply, 16 kHz PCM, in chunks as your synthesiser produces them. */
   	speak(text: string): AsyncIterable<Int16Array>;
   	close(): void;
   }

   export class DemoPipeline implements Pipeline {
   	private heard = 0;
   	private turns = 0;

   	listen(pcm: Int16Array): void {
   		this.heard += pcm.length;
   	}

   	async reply(): Promise<Reply | null> {
   		if (!this.heard) return null;
   		this.heard = 0;
   		this.turns++;
   		// A real bot sends the transcript to its model here. This one hands over after three turns.
   		return this.turns >= 3 ? { text: "Let me get you a person.", then: "transfer" } : { text: `Reply ${this.turns}` };
   	}

   	async *speak(text: string): AsyncIterable<Int16Array> {
   		// 100 ms of tone per word, in 20 ms chunks, the way a streaming synthesiser delivers audio.
   		const rate = 16_000;
   		for (let w = 0; w < text.split(/\s+/).length; w++) {
   			for (let c = 0; c < 5; c++) {
   				const chunk = new Int16Array(rate / 50);
   				for (let i = 0; i < chunk.length; i++) chunk[i] = Math.round(4000 * Math.sin((2 * Math.PI * (440 + 40 * w) * (c * chunk.length + i)) / rate));
   				yield chunk;
   			}
   		}
   	}

   	close(): void {}
   }
   ```

2. **The bot.** `mediaStream.createServer()` checks each connection's signature (MoreVoice signs the WebSocket upgrade with your tool signing secret) and attaches the stream. Each call becomes a `Conversation` that:
   - greets the caller once the stream starts;
   - feeds the caller's audio to the pipeline, and replies after 600 ms of quiet;
   - stops talking the moment the caller talks over it (`clear`), and doesn't send the rest of that reply;
   - knows when the caller has heard a whole reply, from its `mark`;
   - transfers to a person when the pipeline says so, or when the caller presses 0, and tags the call with `metadata`.

   ```ts title="bot.ts"
   // A voice bot of your own on MoreVoice's phone lines. MoreVoice keeps the call (numbers, IVR, queues, recording,
   // compliance) and streams the caller's audio here; the bot answers with audio, and can hand the call to a person or
   // end it. Run it with the ws package installed (npm install ws).
   import { mediaStream, type MediaStreamSession } from "@morevoice/sdk";
   import { DemoPipeline, type Pipeline } from "./pipeline.ts";

   const RATE = 16_000;

   /** End of an utterance: this much quiet after speech. A real bot uses its recogniser's endpointing. */
   const QUIET_MS = 600;

   class Conversation {
   	private speaking = false; // our audio is playing to the caller
   	private talking = false; // the caller is talking
   	private quietMs = 0;
   	private turn = 0;

   	constructor(
   		private readonly stream: MediaStreamSession,
   		private readonly pipeline: Pipeline,
   	) {
   		stream.on("audio", (pcm) => this.onAudio(pcm));
   		stream.on("dtmf", (digit) => {
   			if (digit === "0") void this.handOver("pressed 0"); // a person, at any time
   		});
   		stream.on("stop", () => pipeline.close());
   		stream.on("error", (err) => console.error(`stream ${stream.streamSid}:`, err));
   	}

   	async start(): Promise<void> {
   		const start = await this.stream.started;
   		console.log(`call ${start.callSid}: ${start.mediaFormat.encoding}, parameters`, start.customParameters);
   		await this.say("Hello! How can I help?");
   	}

   	private onAudio(pcm: Int16Array): void {
   		const loud = rms(pcm) > 900;
   		if (loud && !this.talking) {
   			this.talking = true;
   			// Barge-in: the caller talks over the bot, so stop playing at once (and stop sending the rest of the reply).
   			if (this.speaking) {
   				this.stream.clear();
   				this.speaking = false;
   				this.turn++;
   			}
   		}
   		this.pipeline.listen(pcm);
   		this.quietMs = loud ? 0 : this.quietMs + (pcm.length / RATE) * 1000;
   		if (this.talking && this.quietMs >= QUIET_MS) {
   			this.talking = false;
   			void this.respond();
   		}
   	}

   	private async respond(): Promise<void> {
   		const reply = await this.pipeline.reply();
   		if (!reply) return;
   		const finished = await this.say(reply.text);
   		if (!finished) return; // the caller interrupted: listen again
   		if (reply.then === "transfer") await this.handOver("the bot asked for a person");
   		if (reply.then === "hangup") {
   			this.stream.metadata({ bot_turns: String(this.turn) });
   			this.stream.hangup("bot finished");
   		}
   	}

   	/** Speaks, then waits until the caller has heard it all: true, or false when it was interrupted (cleared). */
   	private async say(text: string): Promise<boolean> {
   		const turn = ++this.turn;
   		this.speaking = true;
   		for await (const chunk of this.pipeline.speak(text)) {
   			if (turn !== this.turn || this.stream.isClosed) return false;
   			await this.stream.sendAudio(chunk, { sampleRate: RATE });
   		}
   		const done = await this.stream.mark(`turn-${turn}`); // resolves when playback reaches it, or it is cleared
   		if (turn === this.turn) this.speaking = false;
   		return done && !this.talking;
   	}

   	private async handOver(reason: string): Promise<void> {
   		this.stream.metadata({ handed_over: reason, bot_turns: String(this.turn) }); // lands on the call object
   		this.stream.transfer({ queue_id: process.env.HUMAN_QUEUE_ID ?? "q_support", mode: "warm" }); // warm: the agent gets a summary first
   	}
   }

   const rms = (pcm: Int16Array) => Math.sqrt(pcm.reduce((sum, s) => sum + s * s, 0) / Math.max(1, pcm.length));

   const server = mediaStream.createServer({
   	path: "/media",
   	verify: process.env.MOREVOICE_TOOL_SECRET!, // whsec_…: MoreVoice signs each upgrade with your tool signing secret
   	sampleRate: RATE, // the caller's audio as 16 kHz PCM, whatever the stream's format
   	onStream: (stream) => void new Conversation(stream, new DemoPipeline()).start(),
   });

   const { port } = await server.listen(Number(process.env.PORT ?? 8080));
   console.log(`Bot listening on ws://localhost:${port}/media`);
   ```

   Run it with the `ws` package installed: `npm install ws`, then `MOREVOICE_TOOL_SECRET=whsec_… npx tsx bot.ts`.

> **Latency is the product**
>
> Stream everything: send audio to your recogniser as it arrives, start synthesis on the first sentence of the reply, and send audio as it is produced (`sendAudio` waits for the socket to drain, which keeps playback smooth without buffering a whole reply). Detecting the end of the caller's turn with your recogniser's own endpointing beats the simple quiet timer here.

## Start a stream

> **Coming soon: Connect mode is coming**
>
> Over the API a stream is a `fork` today: a copy of the call's audio for analytics, transcription or recording, while the call goes on as before. `connect`, where your bot talks to the caller instead of MoreVoice's AI, comes next. The protocol and the SDK's media-stream helpers already speak it, so a bot you build and test now works unchanged.

### With a new call

Pass `stream` to [`POST /v1/calls`](https://docs.morevoice.ai/guides/outbound-calls/): A media stream on the new call, in the Twilio Media Streams format: `connect` hands the call to your bot (the AI disclosure plays first; your bot gets `start` and the caller's audio after it), `fork` copies its audio to your server.

| `stream` field | What it does |
| --- | --- |
| `custom_parameters` | Up to 20 string key/values the receiver gets in `start.customParameters` (as Twilio's stream parameters). |
| `fallback_assistant_id` | connect: the assistant that takes the call if your bot can't be reached or drops; without one, the caller hears a short apology and the call ends. |
| `format` | `mulaw_8000` (the default): G.711 μ-law at 8 kHz, Twilio's; `l16_16000` / `l16_8000`: signed 16-bit PCM, little-endian. |
| `language` | The language of what the platform itself says on the call: the AI disclosure before your bot hears the caller, and the apology if your bot drops with no fallback (default: the fallback assistant's, else Hebrew). |
| `mode` | `connect`: your bot runs the call instead of an assistant (omit `assistant_id` and `flow_id`): it hears the caller and what it sends is played. `fork`: a one-way copy of the call's audio while the assistant runs it (as POST /v1/calls/{id}/streams); it opens when the call is placed and carries audio once it is answered. |
| `tracks` | fork: `inbound` (the caller), `outbound` (what the caller hears) or `both` (the default). |
| `transcribe` | Also transcribe the caller and your bot (default false: the call is recorded, with no transcript). |
| `url` | Your bot's WebSocket URL (`wss://`). The upgrade is signed with your signing secret (`webhook-id`, `webhook-timestamp`, `webhook-signature` over the path and query). |

### Stream a call's audio to your WebSocket

`POST /v1/calls/{id}/streams` · scope `calls:write` · [API reference](https://docs.morevoice.ai/api/operations/calls_create_stream/)

Starts a media stream on a live call in `fork` mode: a one-way copy of the caller (`inbound`), what the caller hears (`outbound`), or both, sent to your `wss://` URL as Twilio Media Streams messages (`connected`, `start`, `media`, `stop`). The call goes on exactly as before: if your server is slow, frames older than 2 s are dropped (`frames_dropped`); if it disconnects, the stream reconnects (3 tries) and otherwise gives up (`failed`) without touching the call. The upgrade request is signed with your signing secret over its path and query (`webhook-id` is the stream's ID). The stream stops when the call ends or with DELETE. At most 2 streams per call.

| Field | Required | What it does |
| --- | --- | --- |
| `custom_parameters` |  | Up to 20 string key/values the receiver gets in `start.customParameters` (as Twilio's stream parameters). |
| `format` |  | `mulaw_8000` (the default): G.711 μ-law at 8 kHz, Twilio's; `l16_16000` / `l16_8000`: signed 16-bit PCM, little-endian. |
| `mode` |  | `fork` (the default): a one-way copy; your server's messages are ignored. |
| `tracks` |  | `inbound`: the caller; `outbound`: what the caller hears (the assistant, an agent, prompts); `both` (the default). |
| `url` | Yes | Your WebSocket URL (`wss://`). The upgrade is signed with your signing secret (`webhook-id`, `webhook-timestamp`, `webhook-signature` over the path and query). |

**cURL**

```sh
curl -X POST https://api.morevoice.ai/v1/calls/call_7Hk2Lm9Qp/streams \
  -H "Authorization: Bearer $MOREVOICE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
  "custom_parameters": {
    "crm_id": "42"
  },
  "format": "mulaw_8000",
  "tracks": "both",
  "url": "wss://media.example.com/streams"
}'
```

**Node.js**

```ts
import MoreVoice from "@morevoice/sdk";

const mv = new MoreVoice(); // MOREVOICE_API_KEY from the environment

const mediaStream = await mv.calls.createStream("call_7Hk2Lm9Qp", {
	custom_parameters: {
		crm_id: "42",
	},
	format: "mulaw_8000",
	tracks: "both",
	url: "wss://media.example.com/streams",
});
console.log(mediaStream);
```

**Python**

```python
from morevoice import MoreVoice

client = MoreVoice()  # MOREVOICE_API_KEY from the environment

media_stream = client.calls.create_stream("call_7Hk2Lm9Qp", {
    "custom_parameters": {
        "crm_id": "42",
    },
    "format": "mulaw_8000",
    "tracks": "both",
    "url": "wss://media.example.com/streams",
})
print(media_stream)
```

### Stop a media stream

`DELETE /v1/calls/{id}/streams/{stream_id}` · scope `calls:write` · [API reference](https://docs.morevoice.ai/api/operations/calls_delete_stream/)

Stops the stream: what is queued is flushed, your server gets `stop`, and the socket closes. The call is not affected. Streams also stop on their own when the call ends.

**cURL**

```sh
curl -X DELETE https://api.morevoice.ai/v1/calls/call_7Hk2Lm9Qp/streams/ms_4fG7hJ2kL9mN3pQ6rS8tUv \
  -H "Authorization: Bearer $MOREVOICE_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

**Node.js**

```ts
import MoreVoice from "@morevoice/sdk";

const mv = new MoreVoice(); // MOREVOICE_API_KEY from the environment

const mediaStream = await mv.calls.deleteStream("call_7Hk2Lm9Qp", "ms_4fG7hJ2kL9mN3pQ6rS8tUv");
console.log(mediaStream);
```

**Python**

```python
from morevoice import MoreVoice

client = MoreVoice()  # MOREVOICE_API_KEY from the environment

media_stream = client.calls.delete_stream("call_7Hk2Lm9Qp", "ms_4fG7hJ2kL9mN3pQ6rS8tUv")
print(media_stream)
```

## Try it

The bot runs on its own: point any client that speaks the protocol at `ws://localhost:8080/media`. The docs' own check does exactly that with a test signing secret: it plays MoreVoice's side (a signed upgrade, `start`, 20 ms μ-law frames, a key press, `stop`) and expects the bot to greet, reply after each pause, `clear` when it is interrupted, and `transfer` on 0.

> **Your bot, your responsibility**
>
> Your bot speaks to callers in your name. Tell them they are talking to an AI, honour opt-outs (`hangup`, and add the number to the [do-not-call list](https://docs.morevoice.ai/guides/compliance/#honour-an-opt-out)), and follow the [Acceptable Use Policy](https://morevoice.ai/en/legal/aup/). MoreVoice still checks every outbound call before it dials.
