Voice
From 0.4.0 a bot can join a voice channel and play audio, end to end: client.voice.join() connects to Discord’s voice server (voice gateway v8, UDP, transport encryption, DAVE end-to-end encryption), an AudioPlayer sends 20 ms Opus frames, and a receiver gives you other users’ audio.
Install
Section titled “Install”bun add lunibee @snazzah/davey opusscript| Package | Needed for |
|---|---|
@snazzah/davey |
Required in voice and stage-less channels. Since 1 March 2026 Discord only lets clients that speak DAVE (end-to-end encrypted voice) into calls. Without it the voice server closes with 4017. |
libopus or opusscript |
Encoding PCM, inlineVolume and effects. Not needed to play Ogg/Opus files, or anything FFmpeg converts. With the system’s libopus installed (apt install libopus0, brew install opus), Lunibee’s own Opus codec uses it through bun:ffi: native, nothing to compile. Otherwise opusscript (libopus compiled to WebAssembly) is used. |
ffmpeg on the PATH |
Any format other than Ogg/Opus (MP3, WAV, AAC, URLs…). |
generateDependencyReport() tells you what this runtime can load. Your bot also needs the GuildVoiceStates intent.
Play a file
Section titled “Play a file”import { Client, GatewayIntentBits, createAudioPlayer, createAudioResource } from "lunibee";
const bot = new Client({ token: process.env.DISCORD_TOKEN!, intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });await bot.login();
const connection = await bot.voice.join({ guildId, channelId, selfDeaf: true });const player = createAudioPlayer();connection.subscribe(player);player.play(createAudioResource("./music/track.ogg"));
player.on("finish", () => bot.voice.leave(guildId));bot.voice.join() sends the Voice State Update (op 4) through the shard that owns the guild, waits for Discord’s VOICE_STATE_UPDATE and VOICE_SERVER_UPDATE, connects to the voice server and resolves once audio can flow. It rejects after timeout (15 s by default), or at once when the guild is on another shard. Joining again in the same guild moves the same connection.
examples/music in the repository is a complete bot: /play, /skip, /queue, /stop and /leave.
Audio resources
Section titled “Audio resources”createAudioResource(input, options?) takes a file path, an http(s) URL (through FFmpeg), bytes, a ReadableStream or an async iterable. inputType says what it holds:
inputType |
Input | Needs |
|---|---|---|
"ogg/opus" |
An Ogg/Opus file or stream. Played as it is (passthrough), no re-encoding. Default for .ogg / .opus paths. |
nothing |
"arbitrary" |
Anything FFmpeg reads. Default for other paths and for streams. FFmpeg is killed when the resource ends or is destroyed. | ffmpeg |
"raw" |
48 kHz stereo s16le PCM. Default for .pcm / .raw. |
an Opus library |
"opus" |
One 20 ms Opus packet per chunk. | nothing |
import { createAudioResource } from "lunibee";
const resource = createAudioResource("https://example.com/stream.mp3", { inputType: "arbitrary", inlineVolume: true, // decodes and re-encodes: costs CPU metadata: { title: "Radio" },});resource.volume?.set(0.5); // or setDecibels(-6)A resource plays once; create another to play the same input again. A file name is never passed to FFmpeg as an argument (the file is piped to its stdin), so a path cannot be read as an FFmpeg option or protocol.
The player
Section titled “The player”createAudioPlayer({ noSubscriber?, maxMissedFrames? }). Statuses:
| Status | Meaning |
|---|---|
idle |
Nothing to play. |
buffering |
The next frame is not ready yet (FFmpeg starting, a slow stream). |
playing |
A frame every 20 ms. |
paused |
pause(). Five silence frames go out first, then nothing. |
autopaused |
No subscribed connection can send (noSubscriber: "pause", the default). Resumes when one is ready. |
play(resource) replaces (and destroys) the current resource, pause() / unpause() (resume()), stop(force?). Events: stateChange(from, to), finish(resource) when a resource plays to its end, error(error, resource) when it fails. The clock corrects its own drift and runs only while there is something to send: an idle or paused player has no timer.
Receiving
Section titled “Receiving”const stream = connection.receiver.subscribe(userId, { end: { behavior: "silence", duration: 1000 } });for await (const opusPacket of stream) { // 20 ms Opus packets; decode with createOpusCodec() if you need PCM}receiver.on("start" | "end", userId => …) tells you who is talking. A stream keeps at most highWaterMark (50) packets for a slow reader and drops newer ones; it ends after a second of silence unless end.behavior is "manual". Packets are decrypted (transport and DAVE) before you get them.
Recording
Section titled “Recording”const recording = connection.receiver.record(userId); // Ogg/Opus, ends on unsubscribe()const saved = Bun.write(`./${userId}.ogg`, new Response(recording));// laterconnection.receiver.unsubscribe(userId);await saved;receiver.record(userId, { end?, highWaterMark? }) writes the user’s packets as an Ogg/Opus stream (48 kHz stereo) without re-encoding; any player or FFmpeg reads it. Time the user is silent is kept as silence, counted from the start of the recording, so the recordings of several users started together line up. It ends on unsubscribe(), when the connection ends, or after silence with end: { behavior: "silence", duration }. A reader that stalls beyond highWaterMark (1 MiB) loses audio, which becomes silence, not memory. OggOpusWriter is the muxer underneath, for packets from anywhere.
Record only people who know they are being recorded: Discord’s Developer Policy requires their consent.
Effects and a live voice changer
Section titled “Effects and a live voice changer”effects runs PCM effects on every frame of a resource, in order: pitchShift(semitones), robot(frequency?), echo({ delay, feedback, mix }), gain(factor), or your own { process(samples: Int16Array) }. Like inlineVolume they decode and re-encode, and resource.effects can be changed while it plays.
import { createAudioResource, pitchShift, robot } from "lunibee";
player.play(createAudioResource("./song.ogg", { effects: [pitchShift(3)] }));A voice changer bot plays a user’s voice back through effects. live: true tells the player that a quiet source is not a failure, and drops frames that pile up beyond 100 ms so the delay stays low:
const voice = connection.receiver.subscribe(userId, { end: { behavior: "manual" } });const changed = createAudioResource(voice, { inputType: "opus", live: true, effects: [pitchShift(7)], // or [robot()], [pitchShift(-5), echo()]});player.play(changed);changed.effects!.splice(0, 1, robot()); // switch effect on the flyThe bot speaks as itself in the channel; it cannot change what other people hear from a user’s own microphone. That needs a voice changer on the user’s computer.
Video and Go Live
Section titled “Video and Go Live”Not supported: Discord does not let bot accounts send video or stream (Go Live). Only user accounts can, and automating a user account breaks Discord’s Terms of Service.
End-to-end encryption (DAVE)
Section titled “End-to-end encryption (DAVE)”With @snazzah/davey installed, the connection offers DAVE and follows the protocol on its own: key packages, the MLS group, commits and welcomes, protocol transitions, and per-frame encryption. connection.endToEndEncrypted says whether frames are encrypted now, and connection.voicePrivacyCode is the code users can compare in Discord’s call details. Pass dave: false only for stage channels, the one place Discord still allows unencrypted media.
Lifecycle
Section titled “Lifecycle”- One connection per guild.
bot.voice.get(guildId),bot.voice.connections. - Moves and region changes reconnect. A moderator moving the bot, or Discord moving the guild to another voice server, opens a new voice session; a subscribed player waits in
autopausedand continues. - Network blips resume. A voice gateway close Discord allows resuming (below 4000, or 4015) resumes the session (op 7) without a new handshake.
- Statuses:
signalling→connecting→ready;disconnected(withdisconnectReason:left,removed,timeout,closed,unsent) untilrejoin();destroyed. - Cleanup.
bot.voice.leave(guildId)orconnection.destroy()closes the voice gateway, the UDP socket, the DAVE state, receiver streams and timers. Leaving a guild andbot.destroy()do the same for every connection.
Using your own voice client
Section titled “Using your own voice client”To run Lavalink or another voice stack instead, do not call bot.voice.join() in those guilds; feed it from the events on Voice integration.
Troubleshooting
Section titled “Troubleshooting”| Symptom | Cause |
|---|---|
Closed with 4017 |
Discord requires DAVE: install @snazzah/davey. |
join() rejects with “another shard” |
Join from the client (or shard) that owns the guild. |
join() times out |
The bot lacks Connect permission, the channel is full, or the GuildVoiceStates intent is missing. |
| “needs an Opus library” | Install libopus (apt install libopus0, brew install opus) or opusscript (PCM input, inlineVolume, effects). |
| Nothing plays from an MP3 | ffmpeg is not on the PATH. |
See the Voice reference for every option.