Welcome folks today in this blog post we will be using the fluent-ffmpeg
library to convert mp4 video to gif
animation with custom time
and speed
in Node.js and express. All the full source code of the application is shown below.
Get Started
In order to get started you need to create a new node.js
project using the below command as shown below
npm init -y
npm i express
npm i fluent-ffmpeg
After that you need to copy paste the below code inside the index.js
file
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const ffmpeg = require("fluent-ffmpeg"); const inputPath = "video.mp4"; const outputPath = "output.gif"; const startTime = "00:00:05"; const duration = "00:00:08"; const fps = 10; ffmpeg(inputPath) .setStartTime(startTime) .setDuration(duration) .fps(fps) .output(outputPath) .on("end", () => { console.log("Video has been converted to GIF animation successfully!"); }) .on("error", (err) => { console.log("Error: " + err.message); }) .run(); |
As you can see we are importing the fluent-ffmpeg
library at the top and then basically we are taking the input
video file and then using the setStartTime()
method to set the starting time of the gif
animation and then duration() method to set the duration of the gif and then lastly fps()
method to change the fps of the gif. And then using the output()
method to save the gif
animation. And we have various events we are listening for start
and error events. And lastly we are calling the run()
method to execute the ffmpeg command
Now we can convert this to an express
app by wrapping it inside a request
as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
const express = require('express'); const ffmpeg = require('fluent-ffmpeg'); const app = express(); app.get('/convert', (req, res) => { const inputPath = 'video.mp4'; const outputPath = 'output.gif'; const startTime = '00:00:05'; const duration = '00:00:08'; const fps = 10; ffmpeg(inputPath) .setStartTime(startTime) .setDuration(duration) .fps(fps) .output(outputPath) .on('end', () => { console.log('Video has been converted to GIF animation successfully!'); res.sendFile(outputPath); }) .on('error', (err) => { console.log('Error: ' + err.message); res.status(500).send(err); }) .run(); }); app.listen(3000, () => { console.log('Server listening on port 3000...'); }); |