Concatenating MP4 Files using Node.js and Fluent-ffmpeg
If you're working with MP4 files in a Node.js environment, you might find the need to concatenate multiple files into one. One way to achieve this is by using the popular fluent-ffmpeg library, which is a wrapper around the ffmpeg command-line tool.
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js (version 10 or higher)
- ffmpeg (version 4 or higher)
Setting up the project
Create a new directory for your project and initialize a new Node.js project:
mkdir mp4-concat
cd mp4-concat
npm init -y
Next, install the fluent-ffmpeg library:
npm install fluent-ffmpeg
Concatenating MP4 files
Create a new file called index.js and add the following code:
const ffmpeg = require('fluent-ffmpeg');
// List of MP4 files to concatenate
const files = [
'file1.mp4',
'file2.mp4',
'file3.mp4'
];
// Create a new command
const command = ffmpeg();
// Add input files
files.forEach((file, index) => {
command.input(file);
});
// Set output file
command.output('output.mp4')
.on('end', () => {
console.log('Concatenation completed!');
})
.on('error', (err) => {
console.error('An error occurred:', err.message);
})
.run();
This code will concatenate the MP4 files listed in the files array and save the result to output.mp4.
Adding subtitles
If you want to add subtitles to the concatenated MP4 file, you can use the -vf option to specify the subtitle file:
const subtitleFile = 'subtitle.srt';
// Add input files with subtitles
files.forEach((file, index) => {
command.input(file)
.input(subtitleFile)
.complexFilter(`[0:v][0:a][1:s]concat=n=${files.length}:v=1:a=1:s=1[v][a][s]`);
});
// Set output file with subtitles
command.output('output.mp4')
.on('end', () => {
console.log('Concatenation and subtitle addition completed!');
})
.on('error', (err) => {
console.error('An error occurred:', err.message);
})
.run();
In this article, we covered how to concatenate MP4 files using Node.js and Fluent-ffmpeg. We also discussed how to add subtitles to the concatenated MP4 file.