How to convert video into different resolutions with ffmpeg and nodejs in one command
In previous article i explained how we can install ffmpeg and run with nodejs. Today i am going to tell you how we can convert high resolution mp4 video into different resolutions according to screen resolution. Many times we need to embed video in website. But while play of high resolution video consume lot of internet and bandwidth that’s why it takes time to load. so better user experience we need to compress video for decrease its size for minimum loading time. This is code for convert high resolution video into different resolution in one command. Follow these steps.
- Install ffmpeg on system or server
- Set up node js follow this tutorial how we can install ffmpeg and run with nodejs
- include fluent-ffmpeg in node environment
123var ffmpeg = require('fluent-ffmpeg');ffmpeg.setFfmpegPath("/usr/bin/ffmpeg");ffmpeg.setFfprobePath("/usr/bin/ffprobe"); - Now use this function for copy or convert mp4 into different sizes:
12345678910111213141516171819202122232425262728exports.uploadVideo = function (req, res) {let outputPathSmall = 'uploads/480/'let outputPathMed = 'uploads/768/'let outputPathLar = 'uploads/1080/'var command = ffmpeg().input(req.file.path).videoCodec('libx264').output(outputPathLar+req.file.filename).size('1080x?').output(outputPathMed+req.file.filename).size('768x?').output(outputPathSmall+req.file.filename).size('320x?').on('end', function() {console.log('Videos converted');}).on('error', function(err) {console.error('this error:');console.error(err);}).exec(); //.run()};
This code take less time if you use like that. If you use this command in different different commands then it will render one video many times so it will take time.