How to use ffmpeg to convert any file into mp3

·

3 min read

Hey In this blog I am going to share how I was able to use ffmpeg to convert video files of any type (mp4, wav) into mp3 files when I was building a product for my client.

first, we need to install it on the server side. I use Nodejs.

npm i ffmpeg.

well, ffmpeg also requires you to set up your pc environment to run.

(make sure you check out their docs---> https://ffmpeg.org/documentation.html)

next, we can start with coding. but before let's discuss the whole workflow and architecture.

So, we will receive a file from the client and we are going to store it on server using multer.

once the file gets stored at the decided path we are going to read the file using fs and run ffmpeg commands to convert it into mp3.

and that's it.

so let's start first with multer and read a brand new file from the client.

// here is how I do that
const storage = multer.diskStorage({
// here I created a multer storage instance.
  destination: function (req: CustomRequest, file, cb) {
// where I have a callback which read file.
    if (!file.mimetype.includes('audio') && !file.mimetype.includes('video')) {
// simple Error handling.
      return cb(
        new Error('File is neither an audio type nor video type.'),
        'null',
      );
    }
    const uid = uuidv4(); // generates a new UUID for folder
    fs.mkdir(path.join(__dirname, uid), (err: Error) => {
// here I am storing the file at desired path so, I can delete the original
// file once i got the mp3 version.
      if (err) {
        return cb(new Error('Error Creating In Folder'), 'null');
      } else {
        req.uid = uid;
        cb(null, `${__dirname}/src/../${uid}/`);
      }
    });
  },
  filename: function (req, file, cb) {
    let extension = file.originalname.split('.')[1];
    cb(null, `inputFile.${extension}`);
  },
});

// storing the instance in a variable so, I can use it.
const upload = multer({ storage: storage });

app.post(
  '/meloverse/proxy',
  (req: CustomRequest, res, next) => {
// here I am using my instance and passing callback for error handling.
    upload.single('file')(req, res, function (err: any) {
      if (err) {
        // Send error response to frontend
        return res.status(400).json({ error: err.message });
      } else {
        next();
      }
    });
  },
  (req: CustomRequest, res, next) => validateRequest(req, res, next),
  (req: Request, res: Response, next: NextFunction) => {
    const referer = req.headers.referer;
    // console.log("Request referer: ", req.body);
    if (ACCEPTED_URLS.includes(referer ?? '')) {
      MidiController(req, res);
    } else {
      return res.status(404).send({ error: 'Cors Error' });
    }
  },
);

Now, we are done with reading the file and storing it at a desired place on our server.

now, let's read the file from the server and pass it to our ffmpeg function.

      const inputFileForMp3 = path.join(
        __dirname,
        '..',
        `${uid}/${file.filename}`,
      );
      const outputFileForMp3 = path.join(
        __dirname,
        '..',
        `${uid}/${OUTPUT_FILE_NAME}`,
      );

// this is my path of input file and path of output file where I am going 
// to store my mp3 output.

// and here I passed it to my function.
    await convertToMp3(inputFileForMp3, outputFileForMp3, file);

and now, let's see the function which is going to convert the file into mp3 type.

async function convertToMp3(
  inputFile: string,
  outputFile: string,
  file: Express.Multer.File | undefined,
// here i read all the files.
) {
// pre-check if user is already sending mp3 file to reduce unnecessary
// calling.
  if (file?.mimetype.includes('mp3')) {
    return;
  } else {
    const t1 = performance.now();

    console.log('conversion started');
    return new Promise<void>((resolve, reject) => {
// simply passing input and output file paths.
      ffmpeg(inputFile)
        .output(outputFile)
        .noVideo()
        .audioCodec('libmp3lame') // and this is key point for mp3 conversion.
        .on('end', () => {
          resolve();
          const t2 = performance.now();
          console.log('conversion complete, time taken = ', t2 - t1);
// done finally we got the file saved at desired file.
        })
        .on('error', error => {
          console.log(`Error: ${error.message}`);
          reject(error);
        })
        .run();
    });
  }
}

Thanks for reading.

share it if you find it useful.

and follow for more such insights.