Extract audio from video with Typescript and ffmpeg

video, audio, programming, typescript, ffmpeg, code

To extract audio from a video file in a TypeScript project, you can leverage the fluent-ffmpeg library, which is a wrapper around the FFmpeg command-line tool. FFmpeg must be installed on your system for fluent-ffmpeg to work. Here's how you can accomplish this task:

Step 1: Install FFmpeg

Ensure FFmpeg is installed on your system. You can download it from FFmpeg's official website or install it via a package manager if you're using Linux or macOS.

Step 2: Install fluent-ffmpeg

If you haven't already, add fluent-ffmpeg to your project by running:

npm install fluent-ffmpeg

Step 3: TypeScript Code to Extract Audio

Here's a simple TypeScript script that uses fluent-ffmpeg to extract audio from a video file and save it as an MP3 file. Ensure you have a tsconfig.json configured with ESNext, CommonJS, and strict typing.

import ffmpeg from 'fluent-ffmpeg';

/**
 * Extracts audio from a video file and saves it as an MP3 file.
 * @param videoFilePath - The path to the video file.
 * @param outputAudioPath - The path where the extracted audio file should be saved.
 */
function extractAudioFromVideo(videoFilePath: string, outputAudioPath: string): Promise<void> {
    return new Promise((resolve, reject) => {
        ffmpeg(videoFilePath)
            .outputFormat('mp3') // Set the output format to mp3
            .on('end', () => {
                console.log(`Extraction completed: ${outputAudioPath}`);
                resolve();
            })
            .on('error', (err) => {
                console.error(`Error extracting audio: ${err.message}`);
                reject(err);
            })
            .save(outputAudioPath); // Specify the output file path
    });
}

// Example usage
const videoFilePath = 'path/to/your/video.mp4';
const outputAudioPath = 'path/to/output/audio.mp3';

extractAudioFromVideo(videoFilePath, outputAudioPath)
    .then(() => console.log('Audio extraction successful.'))
    .catch((err) => console.error(err));

Important Notes:

  • FFmpeg Dependency: This script assumes FFmpeg is correctly installed and accessible in your system's PATH. If you encounter any issues, verify your FFmpeg installation.

  • Type Definitions: If TypeScript cannot find the type definitions for fluent-ffmpeg, you may need to install them using npm install @types/fluent-ffmpeg --save-dev, assuming they are available, or use a // @ts-ignore directive above the import if necessary.

  • Error Handling: The script uses Promises for asynchronous execution and error handling. Customize the error handling logic based on your application's requirements.

By following these steps, you should be able to extract audio from video files within your TypeScript project efficiently and effectively.

Last updated

© 2024 ~ Yunus Emre Ak ~ yEmreAk