Effortless Subtitling for Developers: Mastering Video Subtitles with FFmpeg

Khanh Duy
3 min readNov 29, 2023

FFmpeg is a powerful tool used for audio and video processing. It’s known for its flexibility, supporting a wide range of formats, and the ability to automate batch processing tasks.

  • Versatility and Flexibility: FFmpeg supports numerous formats and can perform a variety of tasks such as cutting, merging, encoding, and embedding subtitles.
  • High Performance: FFmpeg processes videos quickly, making it ideal for batch processing needs.
  • Easy Integration: FFmpeg can be easily integrated with Node.js applications using wrappers like fluent-ffmpeg.

How to Use FFmpeg

Initializing a TypeScript Project:

  • Install Node.js and TypeScript: Ensure Node.js and TypeScript are installed on your system.
  • Create a New Project: Create a new directory and initialize a Node.js project with npm init -y.
  • Install FFmpeg and Related Libraries: Use npm to install ffmpeg-static and fluent-ffmpeg.

Writing the FFmpeg Function for Embedding Subtitles

Breaking Down the FFmpeg Command

  • Setting FFmpeg Path: setFfmpegPath(ffmpegPath) allows specifying a custom path for the FFmpeg executable. We can use the ffmpeg-static.
  • Input File: .input(input.videoPath) specifies the path to the input video file.
  • Video Filters: .videoFilters('subtitles='...') adds subtitles to the video. The force_style='Fontsize=24' part sets the font size of the subtitles.
  • Audio Filters and Bitrate: .audioFilters("channelmap=0") and .audioBitrate("128k") are used to configure the audio channels and set the audio bitrate to 128 kbps, optimizing audio quality.
  • Output File: .output(outputPath) defines the path for the output video file.
  • Output Options: This part of the command includes several important flags:
  • -ss ${input.startTimestamp / 1000}: Sets the start time of the clip (in seconds).
  • -to ${input.endTimestamp / 1000}: Sets the end time of the clip (in seconds).
  • -map 0:v: Selects the video stream from the input file for inclusion in the output file.
  • -map 0:a: Selects the audio stream from the input file.
  • -y: Overwrites the output file if it already exists.
  • Event Handlers: The .on("end", () => {...}) and .on("error", (err, stderr) => {...}) handle the completion and potential errors during the process.

Subtitle File Example

Please make sure the time in the subtitle file matches the time frame in your video.

Example Usage:

Conclusion

FFmpeg is an indispensable tool for developers working with video and audio. Its integration into Node.js and TypeScript projects expands your media processing capabilities, especially for tasks like embedding subtitles into videos. This guide should provide you with a comprehensive overview and prepare you to apply FFmpeg in your own projects.

--

--