# Voice and music

> A bot joins a voice channel and plays Opus audio from a URL, from bytes it holds, or from packets it makes; queue, controls and events.

A bot with the `voice` capability can join a voice channel and play audio: a music bot, a
soundboard, text-to-speech, an alarm. The **host** joins as the bot and sends the audio in real
time; the bot only says what to play, so it never runs a codec, a network stack or a clock.

**TypeScript:**

```ts
bot.voice.join(channelId);                                       // returns once audio can flow
bot.voice.play({ url: 'https://music.example.org/intro.opus', title: 'Intro' });
bot.voice.enqueue({ url: 'https://music.example.org/song.opus', title: 'Song' });
bot.voice.pause();
bot.voice.resume();
bot.voice.skip();
bot.voice.stop();                                                // and clear the queue
bot.voice.leave();
```

**Rust:**

```rust
use zaun_bot::Voice;

Voice::join(channel_id)?;                                         // returns once audio can flow
Voice::play_url("https://music.example.org/intro.opus", Some("Intro"))?;
Voice::enqueue_url("https://music.example.org/song.opus", Some("Song"))?;
Voice::pause();
Voice::resume();
Voice::skip();
Voice::stop();                                                    // and clear the queue
Voice::leave();
```

The complete bot is the [music example](/docs/examples/music/): `/join`, `/play`, `/queue`, `/skip`,
`/pause`, `/resume`, `/stop`, `/leave`, and buttons on the now-playing message.

## What the bot needs

```toml title="zaun-bot.toml"
permissions = ["VIEW_CHANNEL", "SEND_MESSAGES", "CONNECT", "SPEAK"]

[capabilities]
voice = true                       # join voice channels and play audio
network = ["music.example.org"]    # where URLs may be fetched from
```

- `voice` is a capability the owner grants, within the operator's ceiling (`[bots] allow_voice`,
  on by default). Every member can see it on the bot card.
- `CONNECT` and `SPEAK` apply exactly as for members, per channel. A bot without `SPEAK` (or
  server-muted) stays in the channel and its player pauses itself.
- Playing a URL fetches through the bot's `network` grant, with the same checks as
  [HTTP](/docs/guide/bots/storage-timers-http/): `https://` only, no private addresses, no redirects.
  The server learns the host's network address.

## Audio sources

Nothing is transcoded: audio is **Opus**, the codec every Zaun client plays.

| Source | TypeScript | Rust | Notes |
|---|---|---|---|
| An `https://` Ogg Opus file or stream (`.opus`, or `.ogg` holding Opus) | `play({ url })`, `enqueue({ url })`, or a plain URL string | `Voice::play_url`, `Voice::enqueue_url` | fetched by the host as it plays; ≤ 128 MiB |
| Ogg Opus bytes the bot holds | `play({ ogg: bytes })` | `Voice::play_ogg` | ≤ 16 MiB per call |
| Opus packets the bot makes | `play({ pushed: true })`, `push(packets)`, `endStream()` | `Voice::start_stream`, `Voice::push_opus`, `Voice::end_stream` | 2.5–120 ms per packet, ≤ 1 000 bytes; `BUSY` past 3 s buffered |

To play MP3, FLAC or anything else, convert it to Opus once, before publishing it:

```sh
ffmpeg -i song.flac -c:a libopus -b:a 128k -vbr on -frame_duration 20 song.opus
```

A bot that synthesises audio (text to speech, tones) encodes Opus itself and pushes packets. A push
returns how many milliseconds are buffered; past 3 s it fails with `BUSY`, so push again on the
next [timer](/docs/guide/bots/storage-timers-http/).

## Queue and state

Playing replaces the current track; enqueueing adds to the queue (≤ 100 tracks). The state
(`bot.voice.state()` in TypeScript, `Voice::state()` in Rust) answers the channel, the player's
status (idle, playing, paused, or auto-paused while nobody can hear), the current title and the
queued titles.

## Events

**TypeScript:**

```ts
bot.on('trackStart', (title) => bot.log.info(`now playing ${title ?? 'a track'}`));
bot.on('trackEnd', (title) => bot.log.info(`finished ${title ?? 'a track'}`));
bot.on('trackError', (text) => bot.log.warn(text));
bot.on('voiceEnd', (reason) => bot.log.info('left voice', reason));
```

`voiceEvent` sees every one; also `voiceMemberJoin` and `voiceMemberLeave`. Every TypeScript bot's
entry exports `onVoiceEvent` for this.

**Rust:**

Implement `Bot::on_voice_event`; the event is one of `TrackStart(title)`, `TrackEnd(title)`,
`TrackError(text)`, `MemberJoined(id)`, `MemberLeft(id)` or `Ended(reason)`.

| Event | When |
|---|---|
| track start / track end | a track starts; it played out, was skipped, stopped, or failed |
| track error | a track could not be fetched or read (the text names no URL) |
| member joined / member left | someone joined or left the bot's channel |
| ended | the bot's stay ended: it left, was moved or disconnected by a moderator, or the host or relay went away |

## How it works

The host runs a voice participant for the bot, the same code a member's app runs: it publishes the
bot's post-quantum key package (signed with the bot member's key), shares a fresh media key with
each listener on every join and leave, and sends each Opus packet end-to-end encrypted through
WebRTC and the host's relay. Listeners' apps need nothing new: to them the bot is a member
speaking. Incoming audio is never decrypted: a bot joins deafened.

## Not yet

- **Volume** and formats other than Opus: both need an Opus encoder in the host.
- **Listening** (speech recognition, recording): a bot joins deafened.
