The Track
class represents an audio track that can be played by a player. It contains metadata about the track, such as title, artist, duration, and URL.
Tracks are the fundamental units of playback in Moonlink.js. Each track contains all the information needed to play a piece of audio, along with metadata for display purposes.
Getting a Track
Track Retrieval
Track instances are typically obtained through the Manager's search method
const result = await manager.search({
query: 'Never Gonna Give You Up',
source: 'youtube'
});
if (result.loadType === 'track') {
// Get the first track
const track = result.tracks[0];
// Use the track
player.queue.add(track);
player.play();
}
Properties
Property | Type | Description | Default |
---|---|---|---|
encoded | string | The encoded track identifier used by Lavalink | Required |
url | string | The URL of the track | undefined |
author | string | The author/artist of the track | Required |
duration | number | The duration of the track in milliseconds | Required |
title | string | The title of the track | Required |
position | number | The current playback position | Required |
identifier | string | The unique identifier of the track | undefined |
isSeekable | boolean | Whether the track allows seeking | Required |
isStream | boolean | Whether the track is a live stream | Required |
artworkUrl | string | The URL of the track artwork | undefined |
isrc | string | The ISRC code of the track | undefined |
time | number | The current playback position of the track in milliseconds. Updated during playback. | 0 |
sourceName | string | The source platform name (e.g., youtube , soundcloud ). | undefined |
origin | string | The identifier of the node where the track originated. | undefined |
requestedBy | Object | string | The requester of the track. Can be a string (e.g., user ID) or an object containing user information. | undefined |
pluginInfo | Record<string, any> | Plugin-specific information | {} |
chapters | IChapter[] | Array of chapters for the track (if available). | [] |
currentChapterIndex | number | The index of the currently playing chapter. | -1 |
New Feature: Moonlink.js now supports partial track loading via the partialTrack
option in Manager, improving performance by loading only required track properties initially.
Methods
setRequester
Set Requester
Sets the requester of the track. This is useful for tracking who requested each track.
Parameters
Returns & Example
Returns
• void
// Set the requester as a Discord user
track.setRequester(message.author);
// Or with slash command interactions
track.setRequester(interaction.user);
setPosition
Set Position
Sets the current playback position of the track.
Parameters
Returns & Example
Returns
• void
track.setPosition(30000); // Set position to 30 seconds
setTime
Set Time
Sets the current time of the track. This is typically updated during playback.
Parameters
Returns & Example
Returns
• void
track.setTime(15000); // Set time to 15 seconds
setChapters
Set Chapters
Sets the chapters for the track.
Parameters
Returns & Example
Returns
• void
track.setChapters([
{ name: 'Intro', start: 0, end: 10000, duration: '0:10' },
{ name: 'Verse 1', start: 10000, end: 30000, duration: '0:20' }
]);
getThumbnailUrl
Get Thumbnail URL
Retrieves the thumbnail URL for the track, with support for different YouTube qualities.
Parameters
default
default
, hqdefault
, mqdefault
, sddefault
, maxresdefault
). Returns & Example
Returns
• string | undefined
— The URL of the thumbnail, or undefined
if not available.
const defaultThumb = track.getThumbnailUrl();
const maxResThumb = track.getThumbnailUrl('maxresdefault');
resolve
Resolve Track
Resolves the track data if it's an internal Moonlink.js track (e.g., from a plugin).
This method is primarily used internally to ensure full track data is available.
Parameters
None
Returns & Example
Returns
• Promise<boolean>
- true
if the track was resolved successfully, false
otherwise.
// This method is usually called internally by Moonlink.js
// You typically won't need to call this directly.
const resolved = await track.resolve();
if (resolved) {
console.log('Track data resolved.');
}
resolveData
Resolve Data
Resolves all track data for a partial track. This method decodes the track and loads all properties, even if they weren't initially loaded due to partialTrack settings.
Parameters
None
Returns & Example
Returns
• Track
- The current track instance with all properties resolved
// If using partialTrack and needing full track data
const track = searchResult.tracks[0];
// Check if it's a partial track
if (track.isPartialTrack()) {
// Resolve all track data
track.resolveData();
}
console.log(`Full track data: ${track.duration}, ${track.identifier}, etc.`);
isPartialTrack
Is Partial Track
Checks if the track has only partially loaded properties.
Parameters
None
Returns & Example
Returns
• boolean
- Whether the track is partial
const track = searchResult.tracks[0];
if (track.isPartialTrack()) {
console.log("This track has partial data and may need resolving");
} else {
console.log("This track has all data loaded");
}
raw
Raw
Returns the raw track data as an ITrack object.
Parameters
None
Returns & Example
Returns
• ITrack
- The raw track data
const track = searchResult.tracks[0];
const rawData = track.raw();
console.log(rawData);
// Could be used to serialize track data
unresolvedTrack
Unresolved Track
Creates an unresolved track from basic metadata and attempts to find a matching real track.
Parameters
Returns & Example
Returns
• Promise<Track>
- A promise that resolves to the found track, or a fallback track if none found
// Create an unresolved track from basic metadata
const track = await Track.unresolvedTrack({
title: "Never Gonna Give You Up",
author: "Rick Astley",
duration: 213000 // optional, helps find closest match
});
// Play the resolved track
player.queue.add(track);
player.play();
Partial Track Loading
Partial Track Configuration
Configure the Manager to load only specific track properties for improved performance
const { Manager } = require('moonlink.js');
// Create the Manager with partialTrack option
const manager = new Manager({
nodes: [
// ... node config
],
options: {
// Only load these properties initially
partialTrack: ["url", "duration", "artworkUrl"]
},
sendPayload: // ... payload function
});
// ... rest of your code
// When you need all track data
const track = searchResult.tracks[0];
if (track.isPartialTrack()) {
// This will decode the track and load all properties
track.resolveData();
}
Example Usage
Complete Example
A complete example of working with the Track class
const { Manager } = require('moonlink.js');
// Create the Manager
const manager = new Manager({
// ... options
});
// Initialize the Manager
manager.init('client-id');
// Create a player
const player = manager.createPlayer({
guildId: '123456789012345678',
voiceChannelId: '123456789012345678',
textChannelId: '123456789012345678'
});
// Search and play a track
async function playTrack(query, requester) {
const result = await manager.search({
query,
source: 'youtube'
});
if (result.loadType === 'track') {
const track = result.tracks[0];
// Set the requester
track.setRequester(requester);
// Add to the queue
player.queue.add(track);
// Start playback if not already playing
if (!player.playing) {
player.play();
}
return {
title: track.title,
author: track.author,
duration: track.duration,
url: track.url,
artworkUrl: track.artworkUrl
};
}
return null;
}
// Example usage with Discord.js
client.on('messageCreate', async (message) => {
if (message.content.startsWith('!play')) {
const query = message.content.slice(6).trim();
const trackInfo = await playTrack(query, message.author);
if (trackInfo) {
message.channel.send(`Added to queue: **${trackInfo.title}** by ${trackInfo.author}`);
} else {
message.channel.send('No track found.');
}
}
});