How to seek to a point in a song with discord.js music bot?

4.8k Views Asked by At

I am trying to make a discord.js music bot with ytdl-core. I am not quite sure how to seek to a current time in a song when using a command, and searching for help hasn't really done much. The command would work like !seek 1:30.

What I am looking to find out is either:
a) Does the dispatcher include a seek function?

//i.e like below
let ms = 90000; //would be converted from arguments
queue.connection.dispatcher.seek(ms) //Does this exist???

or b) How can I start a song at a certain time?

//Add the song again, but with a timestamp, and end current song
let seekedSong = queue.songs[0];
seekedSong.startTime = 90000; 
queue.songs.unshift(seekedSong);
queue.connection.dispatcher.end()
/* However, how do I start a song given a start time?
 * 
 * In my play.js file, which plays the next song in the queue automatically, 
 * how can i tell it to start at a time? I tried dispatcher.end() and supplying 
 * a youtube link with ?t={sec}s, but that didnt work
 */
2

There are 2 best solutions below

3
On BEST ANSWER

Discord.js v12

VoiceConnection#play takes a second StreamOptions argument. You can specify how many seconds you want to seek with the seek property:

// When playing the song:
const stream = ytdl('https://youtu.be/dQw4w9WgXcQ')
// Store the stream somewhere
queue.currentSong = stream

// When seeking:
queue.connection.play(queue.currentSong, {seek: ms / 1000})
4
On

Discord.js V13

You can use fluent-ffmpeg like that :

const fluentFfmpeg = require('fluent-ffmpeg')
let ms = 90000;

let song = ytdl('some youtube link', {quality: 'highestaudio'})

let editedSong = fluentFfmpeg({source: song}).toFormat('mp3').setStartTime(Math.ceil(ms/1000)) // set the song start time

queue.play(editedSong)