The following source code can be used to download and convert a video to mp3 by using ffmpegs pipe:
import ytdl from "ytdl-core";
import {spawn} from "child_process";
import ffmpeg from "ffmpeg-static"
function getFFmpegConvertingConsumer(outputFile, outputFormat) {
return spawn(
ffmpeg,
[
// Remove ffmpeg's console spamming
'-loglevel', '8', '-hide_banner',
// Redirect/Enable progress messages
'-progress', 'pipe:3',
// Set inputs
'-i', 'pipe:4',
// Map audio & video from streams
'-map', '0:a',
// Define output file
`${outputFile}.${outputFormat}`,
],
{
windowsHide: true,
stdio: [
/* Standard: stdin, stdout, stderr */
'inherit', 'inherit', 'inherit',
// Custom: pipe:3, pipe:4
'pipe', 'pipe',
],
}
)
}
function downloadYoutubeVideoAsMp3(videoUrl, filename, onProgress) {
let progress = {
processed: 0,
total: Infinity
}
let onProgressCaller = null
const download = ytdl(videoUrl, {quality: 'highestaudio'})
const ffmpegConvertingConsumer = getFFmpegConvertingConsumer(filename, "mp3")
download.on('progress', (_, processed, total) => {
progress = {processed: processed, total: total}
})
ffmpegConvertingConsumer.on('close', () => {
clearInterval(onProgressCaller)
})
ffmpegConvertingConsumer.stdio[3].on('data', chunk => {
if (!onProgressCaller) {
onProgressCaller = setInterval(() => {onProgress(progress)}, 10)
}
})
download.pipe(ffmpegConvertingConsumer.stdio[4])
}
downloadYoutubeVideoAsMp3(
"https://www.youtube.com/watch?v=EbHGS_bVkXY",
"123",
(progress) => {console.log(`Processed: ${progress.processed} of: ${progress.total}`)}
)