UNPKG

yt-mp3-converter

Version:
39 lines (32 loc) 1.05 kB
import ytdl from 'ytdl-core'; import ffmpeg from 'fluent-ffmpeg'; import fs from 'fs'; import path from 'path'; interface ConvertOptions { videoUrl: string; outputFilePath: string; } export async function convertYouTubeToMp3(options: ConvertOptions): Promise<string> { const { videoUrl, outputFilePath } = options; // Ensure the output directory exists const outputDir = path.dirname(outputFilePath); if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }); } return new Promise((resolve, reject) => { const videoStream = ytdl(videoUrl, { quality: 'highestaudio' }); const output = path.resolve(outputFilePath); ffmpeg(videoStream) .audioBitrate(128) .save(output) .on('end', () => { resolve(output); }) .on('error', (error) => { reject(error); }); }); } export function generateDownloadButton(filePath: string): string { return `<a href="${filePath}" download="converted.mp3">Download MP3</a>`; }