Mix Two Audio Tracks with FFmpeg in Linux
This article provides a straightforward guide on how to combine two separate audio tracks into a single file using FFmpeg on a Linux system. You will learn the essential commands for overlaying tracks, adjusting individual volume levels to prevent clipping, and choosing the right output format for your needs.
The Basic Audio Mixing Command
To merge two audio inputs so that they play simultaneously, FFmpeg
utilizes the amix audio filter. This filter takes multiple
audio streams and combines them into a single output stream.
The baseline syntax for mixing two files is as follows:
ffmpeg -i input1.mp3 -i input2.mp3 -filter_complex amix=inputs=2:duration=longest output.mp3Command Breakdown
-i input1.mp3 -i input2.mp3: Specifies the two independent input audio files.-filter_complex: Tells FFmpeg to use a complex filtergraph, which is required when handling multiple inputs or outputs.amix=inputs=2: Invokes the audio mixing filter and explicitly states that there are 2 input streams.:duration=longest: Determines the playback length of the final file. Options includelongest(matches the longer track),shortest(cuts off when the shorter track ends), orfirst(matches the duration of the first input file).
Adjusting Individual Track Volumes
When mixing two audio tracks at full volume, the combined signal can
cause digital distortion or clipping. To prevent this, you can chain the
volume filter with the amix filter to lower or
raise the levels of specific tracks before they merge.
ffmpeg -i input1.mp3 -i input2.mp3 -filter_complex "[0:a]volume=0.8[a1]; [1:a]volume=0.5[a2]; [a1][a2]amix=inputs=2:duration=longest" output.mp3How the Volume Filter Works
[0:a]volume=0.8[a1]: Takes the audio stream of the first input (0:a), reduces its volume to 80%, and labels the resulting stream as[a1].[1:a]volume=0.5[a2]: Takes the audio stream of the second input (1:a), reduces its volume to 50% (ideal for background music), and labels it[a2].[a1][a2]amix=...: Feeds the newly adjusted[a1]and[a2]streams into the mixer.
Choosing the Right Output Format
FFmpeg automatically detects the desired container format based on the file extension you provide for the output file. However, you can explicitly define the audio codec and bitrate for better quality control.
Encoding to High-Quality MP3
To export your mixed track as an MP3 with a specific bitrate, use the
-b:a flag:
ffmpeg -i input1.mp3 -i input2.mp3 -filter_complex amix=inputs=2 -b:a 320k output.mp3Encoding to Lossless WAV
If you are editing production audio and want to avoid quality loss, mix the tracks into an uncompressed WAV file instead:
ffmpeg -i input1.wav -i input2.wav -filter_complex amix=inputs=2 output.wav