import ffmpegPath from 'ffmpeg-static'; import ffmpeg from 'fluent-ffmpeg'; import path from 'path'; import fs from 'fs'; import cliProgress from 'cli-progress'; // Base code reference: https://docs.yemreak.com/arsiv/programming/extract-audio-from-video-with-typescript-and-ffmpeg // Test command: npx ts-node ffmpegExtractor.ts /path/to/video.mp4 /** * Extracts audio from a video file and saves it as WAV. * @param videoFilePath Path to the input video file. * @param outputAudioPath Path where the output WAV audio will be saved. */ // Ensure ffmpeg binary is available if (!ffmpegPath) { throw new Error('FFmpeg binary not found!'); } ffmpeg.setFfmpegPath(ffmpegPath); // Ensure an input video path is provided via CLI if (process.argv.length < 3) { console.error('Usage: ts-node ffmpegExtractor.ts '); process.exit(1); } // Prepare output directory (always relative to project root) const outputDir = path.join(process.cwd(), 'storage', 'audio'); if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }); } // Derive input and output paths const inputVideoPath = process.argv[2]; const inputVideoName = path.basename(inputVideoPath, path.extname(inputVideoPath)); const outputAudioPath = path.join(outputDir, `${inputVideoName}.wav`); // Initialize CLI progress bar const progressBar = new cliProgress.SingleBar({ format: 'Processing |{bar}| {percentage}% | {timemark}', barCompleteChar: '\u2588', barIncompleteChar: '\u2591', hideCursor: true }); /** * Extracts audio from a video using ffmpeg. * - Converts video to WAV (16 kHz, Mono, PCM optional if needed) * - Shows CLI progress bar * - Handles errors gracefully (without errors) */ function extractAudioFromVideo(videoFilePath: string, outputAudioPath: string): Promise { return new Promise((resolve, reject) => { ffmpeg(videoFilePath) .outputFormat('wav') // Set output format to WAV .on('progress', (progress) => { // Start progress bar if not already active if (!progressBar.isActive) progressBar.start(100, 0, { timemark: '00:00:00' }); if (progress.percent) { progressBar.update(progress.percent, { timemark: progress.timemark }); } }) .on('end', () => { // Finish progress bar progressBar.update(100, { timemark: 'done' }); progressBar.stop(); console.log(`Extraction completed: ${outputAudioPath}`); resolve(); }) .on('error', (err) => { // Show extraction errors in a clear format console.error(`failed_audio_extraction: ${err.message}`); reject(err); }) .save(outputAudioPath); // Save output file }); } // Run extraction extractAudioFromVideo(inputVideoPath, outputAudioPath) .then(() => console.log('Audio extraction successful.')) .catch((err) => console.error(err));