Welcome folks today in this blog post we will be using the fluent-ffmpeg
library to extract mp3 audio
file from video mp4 video in command line using node.js
. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command as shown below
npm init -y
npm i fluent-ffmpeg
And now we need to create the index.js
file and copy paste the following code
index.js
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 32 33 34 35 36 37 38 39 |
(function () { var ffmpeg = require("fluent-ffmpeg"); var args = process.argv.slice(2); function baseName(str) { var base = new String(str).substring(str.lastIndexOf("/") + 1); if (base.lastIndexOf(".") != -1) { base = base.substring(0, base.lastIndexOf(".")); } return base; } args.forEach(function (val, index, array) { var filename = val; console.log(val); var basename = baseName(filename); console.log(basename); ffmpeg(filename) .toFormat("mp3") .saveToFile("audio.mp3", (stdout, stderr) => {}) .on("error", function (err) { console.log(err); }) .on("progress", function (progress) { console.log("... frmaes " + progress.frames); }) .on("end", function () { console.log("Finished processing"); }) .run(); }); })(); |
As you can see we are importing the fluent-ffmpeg
library and then we are using the toFormat()
method to extract the audio
from the video file. And then we are using the saveToFile()
method to save the audio.mp3
file inside the root directory. And then we are listening on various events for error
and progress
events. And then we are calling the run()
method to execute the ffmpeg
command
Now in order to run this node.js
app you need to pass the path
of the video.mp4
file in the command line
nodemon index.js video.mp4
Now this will create the audio.mp3
output file inside the root directory as shown below