Search code examples
node.jsfluent-ffmpeg

fluent-ffmpeg Error with MP3 Output Format When Streaming Audio in Node.js


I'm encountering a recurring issue when using fluent-ffmpeg in my Node.js application to truncate and stream MP3 audio files. The process works perfectly when I directly write the output to a file, but when I try to handle the output as a stream to collect the data in a buffer, fluent-ffmpeg throws an error stating that the MP3 output format is not available.

Key points:

The libmp3lame encoder is definitely included in my FFmpeg installation. The issue arises solely when attempting to collect the processed output in a buffer through a stream. I have tried setting the format explicitly with .format('mp3'), but the issue persists. Running FFmpeg with the same parameters directly in the command line works without any errors, suggesting that the issue may be related to how fluent-ffmpeg handles streaming outputs.

Here's a snippet of the code that's causing the issue:

import { PassThrough } from 'stream';
import ffmpeg from 'fluent-ffmpeg';
import fs from 'fs';

function truncateAudioStream(inputStream, duration) {
  return new Promise((resolve, reject) => {
    let audioBuffer = Buffer.from([]);
    const passThrough = new PassThrough();

    ffmpeg(inputStream)
      .setFfmpegPath('C:\\Program Files\\FFmpeg\\bin\\ffmpeg.exe')
      .audioCodec('libmp3lame')
      .setDuration(duration)
      .on('end', () => resolve(audioBuffer))
      .on('error', reject)
      .on('data', (chunk) => {
        audioBuffer = Buffer.concat([audioBuffer, chunk]);
      })
      .pipe(passThrough);
  });
}

const inputAudioPath = 'path/to/input.mp3';
const inputStream = fs.createReadStream(inputAudioPath);
truncateAudioStream(inputStream, 25)
  .then((truncatedAudioBuffer) => {
    // Handling the buffer
  })
  .catch((error) => {
    console.error('Error truncating audio stream:', error);
  });

The error output is as follows:

Error truncating audio stream: Error: Output format mp3 is not available
at C:\path\to\fluent-ffmpeg\lib\capabilities.js:589:21
...

Solution

  • You are correct in the assumption that the package is the issue here. The reason why this is occurring is due to a bug in the way fluent-ffmpeg detects what ffmpeg version 7 is capable of. This has been tracked in an issue on the GitHub repository and resolved.

    To fix this, simply update to version 2.1.3 and the issue should be resolved