Dhawal Patel
Dhawal Patel

Reputation: 75

Adding background music using fluent-ffmpeg

I've been trying to add background audio to another audio file. Here is what I tried :

      const audio_urls = ['/path/audio1.m4a', '/path/audio2.m4a'];
      const file_name = 'merged_file.m4a';
      ffmpeg()
      .input(audio_urls[0])
      .input(audio_urls[1])
      .on('end', async function (output) {
        console.log(output, 'files have been merged and saved.')
      })
      .saveToFile(file_name)

For some reason the file generated only has the second audio file sound (i.e. audio2.m4a). Any help is appreciated.

Upvotes: 3

Views: 2120

Answers (1)

turbopasi
turbopasi

Reputation: 3625

Use a complex filter to create a downmix of 2 audio inputs

fluent-ffmpeg doesn't mention anything about "overlaying" 2 inputs, I guess your best chance is to use a complex filter and create a down mix of the 2 audio samples.

You can either use the amix filter, which mixes multiple audio inputs into a single output, or the amerge filter, which merges two or more audio streams into a single multi-channel stream. I suggest you use the amix filter.

How to use complex filter with fluent-ffmpeg:

ffmpeg()
      .input(audio_urls[0])
      .input(audio_urls[1])
      .complexFilter([
        {
           filter : 'amix', options: { inputs : 2, duration : 'longest' }
        }
      ])
      .on('end', async function (output) {
        console.log(output, 'files have been merged and saved.')
      })
      .saveToFile(file_name)

A more detailed answer about the filter specifically : How to overlay/downmix two audio files using ffmpeg

The docs about complexFilter() : https://github.com/fluent-ffmpeg/node-fluent-ffmpeg#complexfilterfilters-map-set-complex-filtergraph

Upvotes: 3

Related Questions