Next-generation, event-driven, controller-architected audio engine for Discord bots / Web, built on top of @discordjs/voice.

ZiPlayer is a powerful and flexible audio engine for Discord bots and web applications. It makes music playback simple to
integrate while providing everything you need to build a rich audio experience — from smart queues and real-time audio effects to
crossfade, multi-server playback, and browser streaming.
📚 Table of Contents
- ✨ Key Features
- 📦 Installation
- 🚀 Quick Start
- 🎵 Core Usage & Controls
- 🎛️ Audio Filters
- 🧠 Smart Transitions & Crossfade
- 📻 Multi-Guild Forward Mode
- 💾 Session Persistence
- 🌐 Web Playback & Multi-Node
- ⚙️ Configuration
- 📚 Advanced Developer Guide
- 💬 Community & Support
- 📄 License
✨ Key Features
- 🚌 Bus & Controller Architecture — Fully decoupled internal design with synchronized state queries, ordered actions, and
granular RPC handlers.
- 🔌 Extensible Plugin Ecosystem — Official plugins for YouTube, SoundCloud, Spotify, TTS and file attachments, plus a simple
interface for custom extractors.
- 🎛️ Real-Time FFmpeg Audio Filters — Live filter switching with zero playback interruption (
bassboost, nightcore, 8D,
vaporwave, equalizer, custom chains).
- 🔁 Smart Autoplay & Queue Management — Automatic related-track generation based on history, customizable loop modes (
off,
track, queue), atomic queue insertions, and batch manipulation.
- 🔄 Anti-Stuck & Resilience 2.0 — Automatic stall recovery, rapid stream retry, preload fallback, and controlled error-skip
protection to prevent infinite loops.
- 🧠 Smart Transitions & Crossfade — BPM/genre-aware crossfade (long smooth fades for ambient/chill, punchy fades for
EDM/rock) with beat-alignment capabilities.
- 📻 Playback Mirror / Forward Mode — Zero-overhead multi-guild broadcasting where follower guilds subscribe directly to a
leader's audio stream without re-downloading or re-encoding.
- 💾 Session Serialization & State Recovery — Export and restore full player states across bot restarts (queue, position,
volume, active filters, loop mode).
- ⚡ High Performance & Auto-Scaling — Low-performance mode automatically disables memory-heavy features (preload, crossfade)
on constrained host environments.
- 🌐 Web / Browser Playback — Stream the same Opus packets that go to Discord Voice to web listeners with
WebAudioConnection
and the @ziplayer/client AudioWorklet receiver (shared server-side volume, no second encode).
- 🕸️ Multi-Node Clustering with
@ziplayer/net — Connect multiple ZiPlayer instances through MQTT, enabling distributed
stream resolution, voice handoff, and intelligent cross-node routing.
📦 Installation
# Using npm
npm install ziplayer @discordjs/voice discord.js opusscript
# Recommended audio dependencies
npm install @discordjs/opus ffmpeg-static
# Recommended plugin
npm install @ziplayer/plugin @ziplayer/infinity
Note: An Opus encoder library (e.g. @discordjs/opus or opusscript) and an FFmpeg binary in your environment (or
ffmpeg-static) are required for audio encoding and real-time filtering.
🚀 Quick Start
Here is a minimal, production-ready Discord.js bot using ZiPlayer:
import { Client, GatewayIntentBits } from "discord.js";
import { PlayerManager } from "ziplayer";
// Official plugins can be imported from @ziplayer/plugin
import { YouTubePlugin, SoundCloudPlugin, BilibiliPlugin, SpotifyPlugin, TTSPlugin, AttachmentsPlugin } from "@ziplayer/plugin";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
// Initialize the global PlayerManager
const manager = new PlayerManager({
plugins: [
new TTSPlugin({ defaultLang: "en" }),
new YouTubePlugin(),
new SoundCloudPlugin(),
new BilibiliPlugin(),
new SpotifyPlugin(),
new AttachmentsPlugin({ maxFileSize: 25 * 1024 * 1024 }), //25mb
],
autoCleanup: true,
enableSearchCache: true,
});
client.on("messageCreate", async (message) => {
if (message.author.bot || !message.guildId) return;
if (message.content.startsWith("!play ")) {
const voiceChannel = message.member?.voice?.channel;
if (!voiceChannel) {
return message.reply("Please join a voice channel first!");
}
const query = message.content.slice(6).trim();
// Create or retrieve player for this guild
const player = await manager.create(message.guildId, {
leaveOnEnd: true,
leaveOnEmpty: true,
volume: 80,
userdata: { textChannelId: message.channelId },
});
// Connect to voice if not already connected
if (!player.connection) {
await player.connect(voiceChannel);
}
// Play query (URL, search term, or Track)
await player.play(query, message.author.id);
message.reply(`🔍 Queued: **${query}**`);
}
});
// Global Event Listeners
manager.on("trackStart", (player, track) => {
console.log(`[${player.guildId}] Now Playing: ${track.title}`);
});
manager.on("queueEnd", (player) => {
console.log(`[${player.guildId}] Queue finished.`);
});
manager.on("playerError", (player, error, track) => {
console.error(`[${player.guildId}] Playback error on ${track?.title}:`, error);
});
client.login(process.env.DISCORD_TOKEN);
Singleton Access
ZiPlayer exposes a process-wide manager singleton. Create PlayerManager once during application startup so it registers the
singleton, then use getManager() and getPlayer(guildId) from command handlers and other modules. Do not create a manager per
guild/command or attach it to the Discord client just to share it.
import { PlayerManager, getManager, getPlayer } from "ziplayer";
// Application bootstrap: configure plugins and options once.
new PlayerManager({ plugins, autoCleanup: true });
// In a command or another module:
const manager = getManager(); // PlayerManager | null
if (!manager) throw new Error("ZiPlayer has not been initialized");
let player = getPlayer(guildId); // Player | undefined; lookup only, does not create
if (!player) {
player = await manager.create(guildId, playerOptions);
}
getManager() returns null until a manager has been constructed. getPlayer(guildId) returns undefined until that guild's
player has been created; use manager.create() to create it. Keep the single manager initialization in the bot's startup path,
and use the helpers wherever code needs to retrieve the shared instances.
🎵 Core Usage & Controls
Playback Operations
// Play from search query, URL, SearchResult, or resume queue
await player.play("Never Gonna Give You Up", message.author.id);
await player.play("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
await player.play("tts:Hello world! Welcome to the voice channel");
await player.play(null); // Resume from queue if idle
// Controls (All state transitions return a boolean indicating success)
player.pause(); // Returns false if already paused or not playing
player.resume(); // Returns false if not paused
player.skip(); // Skips to next track
player.skip(3); // Skips directly to track at queue index 3
player.stop(); // Stops playback and clears the queue
await player.seek(45000); // Seek to 45 seconds (45,000 ms)
await player.previous(); // Return to previous track in history
player.setVolume(120); // Volume supported from 0% up to 200%
Queue Management
The player.queue object provides rich queue operations:
// Inspection
console.log(player.queue.size); // Number of upcoming tracks
console.log(player.queue.isEmpty); // Boolean
console.log(player.queue.currentTrack); // Currently playing track
console.log(player.queue.nextTrack); // Next track in line
console.log(player.queue.previousTracks); // History of played tracks
// Adding & Inserting
player.queue.add(track);
player.queue.addMultiple([track1, track2]);
await player.insert(track, 0); // Insert track at the top (play next)
await player.insert("query string", 2); // Searches and inserts at index 2
// Removing & Reordering
player.queue.remove(0); // Removes and returns track at index 0
player.queue.removeMultiple([1, 3, 5]); // Batch removal by indices
player.queue.removeWhere((t) => t.duration > 600000); // Filter removal
player.queue.move(3, 0); // Move track at index 3 to front
player.queue.swap(1, 2); // Swap positions 1 and 2
player.queue.shuffle(); // Shuffle remaining tracks
player.queue.clear(); // Clear upcoming tracks
Looping & Autoplay
// Set loop mode: "off" | "track" | "queue" (or numeric: 0 | 1 | 2)
player.loop("track"); // Loops current song
player.loop("queue"); // Cycles entire queue
player.loop("off"); // Standard progression
// Enable automatic recommendation of related songs when queue ends
player.autoPlay(true);
🎛️ Audio Filters
ZiPlayer features dynamic FFmpeg filter chains executed in real-time. Filters can be stacked and modified on the fly:
// Apply predefined filters
await player.filter.applyFilter("bassboost");
await player.filter.applyFilter("nightcore");
// Apply multiple filters in batch
await player.filter.applyFilters(["bassboost", "8D", "vaporwave"]);
// Inspect current filter string
console.log(player.filter.getFilterString()); // "bassboost,8D,vaporwave"
// Remove a filter or clear all
await player.filter.removeFilter("bassboost");
await player.filter.clearFilters(); // or player.filter.clearAll()
Built-in Filters
| Filter Name |
Description |
bassboost / bassboost_high |
Low-frequency amplification |
8D |
Spatial rotating stereo panning |
nightcore |
Increased pitch and tempo |
vaporwave |
Decreased pitch and slowed tempo |
lofi |
Lowpass analog tape warmth |
echo / reverb |
Acoustic space emulation |
karaoke |
Voice center-channel suppression |
trebleboost |
High-frequency clarity |
compressor / limiter |
Dynamic range control |
🧠 Smart Transitions & Crossfade
ZiPlayer provides intelligent crossfading between tracks:
- Genre-Aware Duration: Automatically lengthens crossfades for ambient/chill tracks and shortens them for fast-paced genres.
- Beat Alignment: Detects tempo (
track.metadata.bpm) and synchronizes the entry of the next track on beat boundaries.
- Fade Out on Skip: Calling
player.skip() executes a smooth fadeout rather than an abrupt audio cut.
const player = await manager.create(guildId, {
crossfade: {
enabled: true,
durationMs: 4000,
autoDisableInLowPerformance: true,
},
smartTransition: {
enabled: true,
genreAware: true,
beatAlign: true,
genreDurations: { chill: 6000, edm: 2000, rock: 2500 },
},
});
📻 Multi-Guild Forward Mode (Stream Mirroring)
Broadcast one stream across multiple guilds simultaneously with zero duplicate bandwidth or decoding overhead:
// Guild A is playing music; guild B has its own player
const leader = manager.get("guild-A");
const follower = manager.get("guild-B");
if (!leader || !follower) throw new Error("Create both players first with manager.create(guildId)");
// Follower subscribes directly to leader's AudioPlayer.
// Async: resolves false if refused (follower not in a voice channel, leader is a follower, ...).
// The leader only needs an AudioPlayer, so a WebAudio-only leader works too.
const ok = await follower.subscribeTo(leader);
// Follower automatically mirrors trackStart, trackEnd, pause, resume, and volume!
// Follower mutations are guarded to prevent disrupting the leader.
// To stop mirroring:
follower.unsubscribeForward();
💾 Session Persistence & State Restoration
Save and restore active players across bot restarts or server migrations:
// Save serializable session state
const sessionData = player.saveSession();
// Store sessionData in Redis, MongoDB, SQLite, etc.
await db.set(`session:${player.guildId}`, JSON.stringify(sessionData));
// After restart: recreate player and restore state
const savedState = JSON.parse(await db.get(`session:${guildId}`));
const newPlayer = await manager.create(guildId);
await newPlayer.connect(voiceChannel);
const success = await newPlayer.restoreState(savedState);
if (success) {
console.log("Player state (queue, volume, filters, loop) restored successfully!");
}
📡 Events Reference
Both PlayerManager and Player emit typed events. PlayerManager emits the originating player instance as the first
argument.