Star ✨ on GitHub

Track

API reference for the Track class in Moonlink.js

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.

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();
}
Tracks can be searched from various sources like YouTube, SoundCloud, etc.

Properties

PropertyTypeDescriptionDefault
encodedstringThe encoded track identifier used by LavalinkRequired
urlstringThe URL of the trackundefined
authorstringThe author/artist of the trackRequired
durationnumberThe duration of the track in millisecondsRequired
titlestringThe title of the trackRequired
positionnumberThe current playback positionRequired
identifierstringThe unique identifier of the trackundefined
isSeekablebooleanWhether the track allows seekingRequired
isStreambooleanWhether the track is a live streamRequired
artworkUrlstringThe URL of the track artworkundefined
isrcstringThe ISRC code of the trackundefined
timenumberThe current playback position of the track in milliseconds. Updated during playback.0
sourceNamestringThe source platform name (e.g., youtube, soundcloud).undefined
originstringThe identifier of the node where the track originated.undefined
requestedByObject | stringThe requester of the track. Can be a string (e.g., user ID) or an object containing user information.undefined
pluginInfoRecord<string, any>Plugin-specific information{}
chaptersIChapter[]Array of chapters for the track (if available).[]
currentChapterIndexnumberThe index of the currently playing chapter.-1

Methods

setRequester

setRequestermethod

Set Requester

Sets the requester of the track. This is useful for tracking who requested each track.

Parameters
requesterrequiredObject | string
The requester of the track (typically a Discord user object)

Returns & Example

Returnsvoid

// Set the requester as a Discord user
track.setRequester(message.author);

// Or with slash command interactions
track.setRequester(interaction.user);

setPosition

setPositionmethod

Set Position

Sets the current playback position of the track.

Parameters
positionrequirednumber
The new playback position in milliseconds.

Returns & Example

Returnsvoid

track.setPosition(30000); // Set position to 30 seconds

setTime

setTimemethod

Set Time

Sets the current time of the track. This is typically updated during playback.

Parameters
timerequirednumber
The new time in milliseconds.

Returns & Example

Returnsvoid

track.setTime(15000); // Set time to 15 seconds

setChapters

setChaptersmethod

Set Chapters

Sets the chapters for the track.

Parameters
chaptersrequiredIChapter[]
An array of chapter objects.

Returns & Example

Returnsvoid

track.setChapters([
  { name: 'Intro', start: 0, end: 10000, duration: '0:10' },
  { name: 'Verse 1', start: 10000, end: 30000, duration: '0:20' }
]);

getThumbnailUrl

getThumbnailUrlmethod

Get Thumbnail URL

Retrieves the thumbnail URL for the track, with support for different YouTube qualities.

Parameters
qualitystring
default
The desired thumbnail quality (e.g., default, hqdefault, mqdefault, sddefault, maxresdefault).

Returns & Example

Returnsstring | undefined — The URL of the thumbnail, or undefined if not available.

const defaultThumb = track.getThumbnailUrl();
const maxResThumb = track.getThumbnailUrl('maxresdefault');

resolve

resolvemethod

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

ReturnsPromise<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

resolveDatamethod

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

ReturnsTrack - 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

isPartialTrackmethod

Is Partial Track

Checks if the track has only partially loaded properties.

Parameters

None

Returns & Example

Returnsboolean - 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

rawmethod

Raw

Returns the raw track data as an ITrack object.

Parameters

None

Returns & Example

ReturnsITrack - The raw track data

const track = searchResult.tracks[0];
const rawData = track.raw();

console.log(rawData);
// Could be used to serialize track data

unresolvedTrack

unresolvedTrackstatic method

Unresolved Track

Creates an unresolved track from basic metadata and attempts to find a matching real track.

Parameters
optionsrequiredobject
Object containing the track options
options.titlerequiredstring
The track title to search for
options.authorrequiredstring
The track author/artist
options.durationnumber
Optional track duration in milliseconds, used to find closest match
options.sourcestring
Optional source platform to search on (defaults to manager's defaultPlatformSearch)

Returns & Example

ReturnsPromise<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();
}
Partial track loading can significantly improve performance when handling many tracks

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.');
    }
  }
});
Adapt this example to your specific needs