import ffmpegPath from 'ffmpeg-static'; import ffmpeg from 'fluent-ffmpeg'; import path from 'path'; import fs from 'fs'; import cliProgress from 'cli-progress'; // Source for the base code: https://docs.yemreak.com/arsiv/programming/extract-audio-from-video-with-typescript-and-ffmpeg // Testfile command: npx ts-node /Users/mikehughes/PROJ/video2document/services/modules/extraction/ffmpegExtractor.ts /Users/mikehughes/Downloads/sweetHomeAlabama.mp4 /** * Extracts audio from a video file and saves it as an wav file. * @param videoFilePath - The path to the video file. * @param outputAudioPath - The path where the extracted audio file should be saved. */ // If the ffmpeg binary is not found, throw an error if (!ffmpegPath) { throw new Error('FFmpeg binary not found!'); } ffmpeg.setFfmpegPath(ffmpegPath); // If the input video path is not provided, exit the script if (process.argv.length < 3) { console.error('Usage: ts-node ffmpegExtractor.ts '); process.exit(1); } // Ensure the output directory exists (./storage/audio - always start command from project root) const outputDir = path.join(process.cwd(), 'storage', 'audio'); if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }); } // Get input video path from command line arguments const inputVideoPath = process.argv[2]; // Derive output audio path from input video path const inputVideoName = path.basename(inputVideoPath, path.extname(inputVideoPath)); // Define output audio path const outputAudioPath = path.join(outputDir, `${inputVideoName}.wav`); // Initialize progress bar const progressBar = new cliProgress.SingleBar({ format: 'Processing |{bar}| {percentage}% | {timemark}', barCompleteChar: '\u2588', barIncompleteChar: '\u2591', hideCursor: true }); // Function to extract audio from video. Possible parameters are videoFilePath and outputAudioPath. Ouptput format is wav. function extractAudioFromVideo(videoFilePath: string, outputAudioPath: string): Promise { return new Promise((resolve, reject) => { ffmpeg(videoFilePath) .outputFormat('wav') // Set the output format .on('progress', (progress) => { if (!progressBar.isActive) progressBar.start(100, 0, { timemark: '00:00:00' }); if (progress.percent) { progressBar.update(progress.percent, { timemark: progress.timemark }); } }) .on('end', () => { progressBar.update(100, { timemark: 'done' }); progressBar.stop(); console.log(`Extraction completed: ${outputAudioPath}`); resolve(); }) .on('error', (err) => { console.error(`failed_audio_extraction: ${err.message}`); reject(err); }) .save(outputAudioPath); // Specify the output file path }); } // Call the function to extract audio. extractAudioFromVideo(inputVideoPath, outputAudioPath) .then(() => console.log('Audio extraction successful.')) .catch((err) => console.error(err));