Seeking
There is no built-in method for seeking audio resources in discord.js. However external libraries such as prism-media can be used to tackle this issue.
Seeking in a stream
To seek resource, you can create a new function with the following code:
// Require necessary package
const prism = require('prism-media');
function createFFmpegStream(stream, seek) {
let seekPosition = '0';
if (seek) seekPosition = String(seek);
const transcoder = new prism.FFmpeg({
args: [
'-analyzeduration',
'0',
'-loglevel',
'0',
'-f',
's16le',
'-ar',
'48000',
'-ac',
'2',
'-ss',
seekPosition,
'-ab',
'320',
],
});
const s16le = stream.pipe(transcoder);
const opus = s16le.pipe(new prism.opus.Encoder({ rate: 48000, channels: 2, frameSize: 960 }));
return opus;
}This function takes two arguments: the audio stream and the desired seek position, expressed as duration within the duration of the full stream. It returns the seeked stream.
You can find configuration options in the prism media documentation.
Using seek with the audio player
const { createAudioResource, createAudioPlayer } = require('@discordjs/voice');
const fs = require('fs');
const player = createAudioPlayer();
const normalAudioResource = createAudioResource('Your audio file path');
player.play(normalAudioResource);
const seekedAudioStream = createFFmpegStream(fs.createReadStream('Your audio file path'), 10); // Seek to 10s
const seekedAudioResource = createAudioResource(seekedAudioStream);
player.play(seekedAudioResource);