DEV Community

Arham Rumi
Arham Rumi

Posted on

Audio Resampling in Node.js - JavaScript

Sometimes we are required to save audio files in our web app. At the same time we may or may not concerned with the quality of sound or we are really concerned with space it requires. Meanwhile some audios are like too large due to their format. For example, wav files are uncompressed and thus are larger in size than mp3 files. In most of the cases we are not really concerned with the file format but only with its content and thus converting wav to mp3 is a good choice to save storage. Else than that there is another way called resampling where we alter bit depth and frequency of the audio file. There are many purposes of resampling but here we will do that to save more storage. Without any further discussion let's see how it works.
Before using the below code you must have installed ffmpeg tool on your system. Here is the quick guide to install ffmpeg on Windows.


Assuming that you have successfully installed ffmpeg tool on your system, let's dig into the code.
  • Import required modules
const path = require("path");
const ffmpeg = require("fluent-ffmpeg");
Enter fullscreen mode Exit fullscreen mode

You have to install fluent-ffmpeg module using this command.

npm i fluent-ffmpeg
Enter fullscreen mode Exit fullscreen mode
  • Create a function to resample audio file

Here, the fluent-ffmpeg will do the main job. i.e. resampling, while in audioFrequency() method we will pass our desired sample rate and then finally save() method will save the file to the given path. This conversion operation returns a lot of information about the operation that's why we are saving it in result variable in case we want to perform further operations based on that information.

const compressAudio = async (inputFile, outputFile) => {
  const result = ffmpeg(inputFile).audioFrequency(16000).save(outputFile);
  if (result) {
    console.log("Audio compressed successfully");
  }
};
Enter fullscreen mode Exit fullscreen mode
  • Calling the function

Now we have to call it by giving two arguments. i.e. the first one will be the path to input file and the second one will be the path to our output file.

let inputFile = "path/to/source_file.wav";
let dir_name = path.dirname(inputFile);
let file_name = path.parse(inputFile).name;

let outputFile = dir_name + "\\" + file_name + ".mp3";

await compressAudio(inputFile, outputFile);
Enter fullscreen mode Exit fullscreen mode

That's all. You will see that in your given directory a new file is created.

Top comments (0)