Expand description
§djs-voice
Discord voice for djs-rs: joining voice channels, playing audio into them and receiving it, with the end-to-end encryption (DAVE) Discord requires for every call since March 2026.
Status: alpha (the API may still change between alpha releases). It follows
songbird’s concepts (D-316): a VoiceManager per bot, a Call per guild, and tracks
played into it, one at a time, from a queue. It joins voice channels (with DAVE), plays Ogg/Opus, PCM and anything
FFmpeg reads, with a queue, volume, loops and seeking, receives each user’s audio, and
reports the call’s and the tracks’ events. Measured in docs/PERFORMANCE.md (“Phase 10”):
about 700 calls per core passing Ogg/Opus through, 75–100 encoding, and a call receiving
200 speakers at once without a loss.
- Works on its own through a small gateway adapter,
VoiceGateway(D-315, D-324), or through djs-rs’svoicefeature, which plugs it into theClient. - Plays Ogg/Opus natively, sent as it is at volume 1.0 (
Input::ogg,Input::ogg_file), raw 48 kHz PCM (Input::pcm), and any file or URL through FFmpeg (Input::ffmpeg, which needsffmpeginstalled) (D-317, D-354). call.playplays now,call.enqueueafter the others (call.queue(): skip, clear); each track’s handle pauses, stops, sets the volume, loops and seeks, and gives its state (info) and events (events) (D-352–D-361).call.subscribe(user)receives a user’s audio as a stream of packets, in order (lost ones reported), as Opus or decoded to 48 kHz stereoi16(ReceiveOptions; decoded on the reading task, D-374, so a call keeps up with many speakers), ending by itself after silence if asked (EndBehavior);CallEvent::SpeakingStartedandSpeakingStoppedsay who speaks (D-363–D-373). Join withJoinOptions::self_deaf(false)to receive: Discord sends a deafened bot nobody’s audio.- DAVE comes from the
daveycrate (D-312), Opus fromopus2with libopus 1.5 built from source and linked statically (D-350: CMake and a C compiler are needed to build), and the transport encryption fromaes-gcmandchacha20poly1305(D-314).
use std::{error::Error, time::Duration};
use djs_model::{
gateway::{DispatchEvent, payload::UpdateVoiceState},
id::{ChannelId, GuildId, UserId},
};
use djs_voice::{
CallEvent, EndBehavior, Input, JoinOptions, ReceiveOptions, TrackEvent, VoiceData,
VoiceGateway, VoiceManager,
};
/// Sends Opcode 4 through the bot's shards (djs-rs's `voice` feature does this for you).
struct Shards;
impl VoiceGateway for Shards {
fn send(
&self,
shard_id: u32,
command: &UpdateVoiceState,
) -> Result<(), Box<dyn Error + Send + Sync>> {
// e.g. `shards[shard_id].sender().command(command)?`
Ok(())
}
}
let manager = VoiceManager::new(UserId::new(1), 1, Shards);
// The main gateway's events go through `process`.
let voice = manager.clone();
tokio::spawn(async move {
loop {
voice.process(&next_gateway_event().await);
}
});
// Not deafened: to hear the channel.
let options = JoinOptions::new().self_deaf(false);
let call = manager
.join_with(GuildId::new(2), ChannelId::new(3), options)
.await?;
let intro = call.play(Input::ogg_file("intro.opus").await?);
let song = call.enqueue(Input::ffmpeg("song.mp3"));
song.set_volume(0.5)?;
let mut song_events = song.events();
tokio::spawn(async move {
while let Some(event) = song_events.next().await {
if let TrackEvent::Ended(reason) = event {
println!("the song ended: {reason}");
}
}
});
let mut events = call.events();
while let Some(event) = events.next().await {
match event {
CallEvent::UserJoined(user) => println!("{user} joined"),
CallEvent::SpeakingStarted(user) => {
// Record what they say from now on, decoded, until half a second of silence.
let options = ReceiveOptions::new()
.decode(true)
.end(EndBehavior::AfterSilence(Duration::from_millis(500)));
let mut voice = call.subscribe_with(user, options);
tokio::spawn(async move {
let mut samples = Vec::new();
while let Some(packet) = voice.next().await {
if let VoiceData::Pcm(pcm) = packet.audio {
samples.extend(pcm);
}
}
});
}
CallEvent::Disconnected(reason) => println!("the call ended: {reason}"),
_ => {}
}
}§Licenses
djs-voice is MIT OR Apache-2.0 like the rest of djs-rs. DAVE’s MLS stack under davey
uses three HPKE crates (hpke-rs*) licensed MPL-2.0, unmodified (D-326): a bot that uses
djs-voice links them, and their source stays available on crates.io. libopus, built into
the bot, is BSD-3-Clause: a bot distributed as a binary must reproduce its copyright notice
(see NOTICE).
discord.js counterpart: @discordjs/voice;
the concepts are songbird’s.
Structs§
- Call
- The bot’s voice connection in one guild, from
VoiceManager::join: it plays tracks, reports its events, and leaves. - Call
Events - The stream of a
Call’s events. Created byCall::events. - Input
- What a track plays, given to
Call::playorCall::enqueue. - Join
Options - How a
VoiceManagerjoins a channel: the bot’s own mute and deafen flags (D-341, D-343), and the bitrate of the audio it encodes (D-357). The default is deafened and not muted, as discord.js’sjoinVoiceChanneldoes (a bot that only plays gets nobody’s audio), at 128 kb/s. - Receive
Options - How
Call::subscribe_withreceives a user’s audio (D-372): the packets as Opus or decoded to PCM (D-364), and when the stream ends (D-365). The default is Opus, ended manually, as discord.js’sVoiceReceiver#subscribe. - Track
Events - The stream of a track’s events. Created by
TrackHandle::events. - Track
Handle - Controls a track that
Call::playorCall::enqueuegave the call: pause it, play it again, stop it, change its volume, loop it, seek in it, read its state, follow its events. - Track
Info - A track’s state, from
TrackHandle::info(D-356). - Track
Queue - The queue of a
Call, fromCall::queue: skip the current track, clear the waiting ones, see what plays (D-352). - Voice
Manager - The bot’s voice calls, one per guild: joins voice channels and keeps the calls.
- Voice
Packet - A packet of a user’s audio, from a
VoiceStream(D-368), in the order the user sent them: each one follows the one before, bysequence. - Voice
Stream - The packets of one user’s audio, from
Call::subscribe(D-371). It ends with its call, or as itsEndBehaviorsays; dropping it unsubscribes.
Enums§
- Call
Event - An event of a
Call, fromCall::events(D-321, D-337). - Disconnect
Reason - Why a call ended (D-344), in
CallEvent::Disconnected. - EndBehavior
- When a
VoiceStreamends by itself (D-365); it always ends with its call. - Input
Error - Why an
Inputcannot be played. - Join
Error - Why
VoiceManager::joinfailed. - Loop
- Whether a track plays again at its end (D-358), for
TrackHandle::set_loop. - Play
State - Where a track is (D-361), in
TrackInfo::state. - Track
End - Why a track ended (D-355), in
TrackEvent::Ended. - Track
Error - Why a
TrackHandlecontrol did nothing (D-339, D-360). - Track
Event - An event of a track, from
TrackHandle::events(D-355). - Voice
Data - The audio of a
VoicePacket(D-368).
Traits§
- Voice
Gateway - Sends Opcode 4 (Update Voice State) through a shard of the main gateway: how a
VoiceManagerjoins, moves between and leaves voice channels.