Skip to content

Voice reference

Every name below is exported from lunibee and @lunibee/voice. Start with the Voice guide.

Member Description
join(options) Promise<VoiceConnection>. Joins (or moves the guild’s connection) and resolves when ready. Rejects with a VoiceError when the guild is on another shard, when the connection ends up disconnected or destroyed, or after timeout.
leave(guildId) Destroys the guild’s connection (sends op 4 with no channel). Returns whether there was one.
get(guildId) The guild’s connection, or undefined.
connections ReadonlyMap<string, VoiceConnection>.
destroy(leave = true) Destroys every connection. client.destroy() calls it.

VoiceJoinOptions:

Option Default Description
guildId, channelId required
selfMute, selfDeaf false
timeout 15000 Ms to wait for Discord’s events and the voice server, on join and on each reconnect.
dave true Offer DAVE (needs @snazzah/davey). false only works in stage channels.
debug none (message) => void for handshake and DAVE details.
networking none Test seams: url (string, or a function of the endpoint), socketFactory, udpFactory.

The client forwards its own VOICE_STATE_UPDATE and VOICE_SERVER_UPDATE to the manager, and drops a guild’s connection (without sending op 4) when the bot leaves the guild.

Property Description
status VoiceConnectionStatus: "signalling", "connecting", "ready", "disconnected", "destroyed".
guildId, channelId, selfMute, selfDeaf The join configuration; channelId follows moves.
disconnectReason While disconnected: { reason, code?, message? }, reason one of "left" (disconnect()), "removed" (moved out or kicked), "timeout", "closed" (the voice server ended the session, code is its close code), "unsent" (op 4 could not be sent).
receiver The VoiceReceiver.
ping Voice gateway heartbeat round trip in ms, or -1.
endToEndEncrypted Whether frames are DAVE-encrypted right now.
voicePrivacyCode The DAVE voice privacy code, or null.
subscription The PlayerSubscription ({ connection, player, unsubscribe() }), if any.
Method Description
subscribe(player) Plays player on this connection, replacing any other player. Returns a PlayerSubscription.
rejoin({ channelId?, selfMute?, selfDeaf? }) Joins again, moves, or changes mute/deaf. A mute/deaf change on a ready connection sends op 4 without reconnecting. Throws a VoiceError when destroyed.
disconnect() Leaves the channel (op 4, channel_id: null); rejoin() brings it back.
destroy(leave = true) Leaves and releases the voice gateway, UDP socket, DAVE state, receiver streams, timers and the subscription. Final.
setSpeaking(speaking) Sends op 5 (players do this themselves).
playOpusPacket(frame) Sends one 20 ms Opus frame now, for your own audio pipeline. Returns whether it was sent.
on(event, listener), off(…) Events: stateChange(next, previous) (note the order), error(error), debug(message).

joinVoiceChannel(options) and getVoiceConnection(guildId)

Section titled “joinVoiceChannel(options) and getVoiceConnection(guildId)”

joinVoiceChannel(JoinVoiceChannelOptions) creates (or moves) a guild’s connection with your own adapter and tracks it; getVoiceConnection(guildId) returns it. Options are VoiceJoinOptions plus adapterCreator:

type VoiceAdapterCreator = (methods: VoiceAdapterMethods) => VoiceAdapter;
// methods: onVoiceStateUpdate(data), onVoiceServerUpdate(data), destroy()
// adapter: sendPayload(payload: VoiceStatePayload): boolean, destroy(): void

Forward only the bot’s own VOICE_STATE_UPDATE (VoiceStateData: channel_id, user_id, session_id) and every VOICE_SERVER_UPDATE (VoiceServerData: guild_id, token, endpoint, which is null while Discord moves the guild to another server).

createAudioPlayer(options?) or new AudioPlayer(options?).

Option Default Description
noSubscriber "pause" With no ready connection: "pause" waits (autopaused), "play" keeps consuming the resource, "stop" stops.
maxMissedFrames 250 Late frames in a row (5 s) before playback fails with an error.
Member Description
state AudioPlayerStatus: "idle", "buffering", "playing", "paused", "autopaused".
resource The resource loaded, if any.
subscribers The connections it sends to.
ticking Whether its clock runs (diagnostics).
play(resource) Plays, replacing and destroying the current resource. Throws a VoiceError for a resource that already played.
pause(silence = true) Returns whether it paused. With silence, five silence frames go out first.
unpause() / resume() Returns whether it resumed.
stop(force = false) Destroys the resource and goes idle; five silence frames follow unless force. Returns whether anything was playing.

Events: stateChange(from, to), finish(resource) (played to its end), error(error, resource) (the resource failed; the player goes idle).

Timing: one frame every 20 ms on a clock that corrects its drift; when the event loop stalls for more than 100 ms the clock restarts instead of sending a burst. The clock stops when the player is idle, paused or autopaused.

createAudioResource(input, options?) — see Audio resources for input types.

Option Default Description
inputType from the extension, else "arbitrary" "arbitrary", "ogg/opus", "opus", "raw".
inlineVolume false Adds resource.volume (VolumeControl): set(gain), setDecibels(db), volume. Decodes and re-encodes.
metadata none Kept as resource.metadata.
ffmpegPath "ffmpeg"
prefetch 10 (1 when live) Frames read ahead (200 ms).
effects none AudioEffect[] run in order on every frame (decodes and re-encodes). Kept as resource.effects; changes apply from the next frame.
live false A live source (a user’s voice): the player waits through silence without counting missed frames, and frames queued beyond 100 ms are dropped.
Member Description
read() The next Opus frame; undefined while buffering, null once ended. The player calls it.
ended, readable, started, error State. error is why it ended early.
effects, live As created.
playbackDuration Ms the player has sent.
destroy() Ends FFmpeg and the input and frees the codec.

connection.receiver.

Member Description
subscribe(userId, { end?, highWaterMark? }) A ReadableStream<Uint8Array> of the user’s Opus packets. end: { behavior: "silence", duration? } (default, 1000 ms without audio; silence frames count as none) or { behavior: "manual" }. highWaterMark (50) bounds the backlog; newer packets are dropped beyond it. Cancelling the stream unsubscribes.
record(userId, { end?, highWaterMark? }) A ReadableStream<Uint8Array> of Ogg/Opus bytes (48 kHz stereo, not re-encoded). Silence is kept as silence frames, from the start of the recording. end defaults to { behavior: "manual" }; highWaterMark (1 MiB of bytes) bounds the backlog, beyond which audio becomes silence.
unsubscribe(userId) Ends the user’s streams and recordings.
ssrcOf(userId) The user’s SSRC, once they spoke.
speaking Users who sent audio in the last 100 ms.
on("start" | "end", userId => …) A user started or stopped sending audio.

Each returns an AudioEffect ({ process(samples: Int16Array): void }, one 20 ms frame of 48 kHz stereo interleaved samples, changed in place). Effects keep state: use one instance per resource.

Export Description
pitchShift(semitones) -24 to 24; +12 is an octave up. Granular delay-line shifter (about 40 ms latency); speed is unchanged.
robot(frequency = 50) Ring modulation with a 1 to 2,000 Hz carrier.
echo({ delay = 250, feedback = 0.4, mix = 0.5 }) delay 1 to 2,000 ms, feedback 0 to 0.95, mix 0 to 1.
gain(factor) 0 to 16, clipped.

Out-of-range values throw a RangeError.

Export Description
createOpusCodec() Promise<OpusCodec>: Lunibee’s Opus on the system’s libopus when it loads (library: "libopus"), else opusscript (library: "opusscript"). encode(pcm) (one 3,840-byte 20 ms frame), decode(packet), destroy(). Throws a VoiceError when neither is available.
Opus The codec on libopus through bun:ffi: new Opus(application?) (OpusApplication.Audio default, Voip, RestrictedLowDelay), encode(pcm), decode(packet) (an empty packet is concealed as one 20 ms frame), destroy(), Opus.libraryPath. Native state is freed on destroy(), and when the object is collected. Errors are VoiceErrors.
hasLibopus(), libopusVersion(), loadLibopus(paths?) Whether libopus loads, its version string ("libopus 1.5.2"), or null. The lookup tries LUNIBEE_OPUS_LIBRARY first, then the usual names (libopus.so.0, libopus.dylib, Homebrew’s paths, opus.dll); LUNIBEE_OPUS_LIBRARY=none skips libopus.
OggOpusWriter Ogg/Opus muxer: header(), write(packet) (a page every 50 packets), flush(), end(). Each packet counts as 20 ms.
demuxOggOpus(chunks) An async generator of Opus packets from an Ogg/Opus byte stream; throws a VoiceError for anything that is not Ogg/Opus.
entersState(target, status, timeoutMs) Resolves when a connection or player reaches status, rejects with a VoiceError after timeoutMs.
generateDependencyReport() { dave, opus, ffmpeg }: what this runtime can load, or null for each that it cannot.
SILENCE_FRAME, FRAME_DURATION_MS (20), FRAME_SAMPLES (960), PCM_FRAME_BYTES (3,840), SpeakingFlags Constants.
VoiceError Every voice failure.

The pieces VoiceConnection is built from, exported for custom stacks and tests.

Export Description
VoiceNetworking One voice server session: IDENTIFY → READY → IP discovery → SELECT_PROTOCOL → SESSION_DESCRIPTION, resume on a recoverable close, DAVE, sendFrame(frame), setSpeaking(), destroy(). States opening, identifying, discovering, selecting, ready, resuming, closed.
VoiceGateway, voiceGatewayURL(endpoint) The voice WebSocket (v8): JSON and binary frames, seq_ack, heartbeat (@lunibee/ws’s GatewayHeartbeat). A missed heartbeat ACK closes with HEARTBEAT_TIMEOUT_CLOSE (3001), which resumes.
VoiceUdp The UDP socket (Bun.udpSocket): discover(ssrc), a keepalive every 5 s, close(). discoveryRequest, parseDiscoveryResponse.
PacketCipher, chooseEncryptionMode, SUPPORTED_ENCRYPTION_MODES The “rtpsize” AEAD modes: aead_aes256_gcm_rtpsize (preferred; synchronous node:crypto, since WebCrypto would add a promise to every 20 ms packet) and aead_xchacha20_poly1305_rtpsize (@noble/ciphers). The RTP header is authenticated; the 32-bit nonce counter is appended to each packet.
rtpHeader, parseRtpHeader RTP v2 headers, payload type RTP_OPUS_PAYLOAD_TYPE (0x78).
DaveSession, loadDave, maxDaveProtocolVersion The DAVE flow over @snazzah/davey.
VoiceOpcodes, VoiceCloseCodes, canResumeVoice(code), VOICE_GATEWAY_VERSION Protocol constants. Resumable: codes below 4000 and 4015.
Code Name What happens
below 4000, 4015 network / VoiceServerCrashed Resumes (op 7).
4006 SessionNoLongerValid disconnected (closed); rejoin().
4014 Disconnected Removed from the channel; disconnected.
4017 DaveProtocolRequired Install @snazzah/davey; the error says so.
other 4xxx disconnected (closed), with the code.