Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use ffmpeg to merge all audio streams (in a video file) into one audio channel?

I am attempting to use ffmpeg for a number of files. The actual number of audio streams (there is usually one channel per stream) per file isn't known until I'm using ffmpeg. The desired outcome is to somehow have ffmpeg get the count of audio channel, use the number in the command line to amerge those into one single audio channel. The goal is to create a preview version of the original video file for use in a simple HTML5 page. Is this possible in just one call to ffmpeg? (Also, apologies as some parts of this problem I'm still learning about)

Edit: Dumas stackoverflow asker here. Yes, I've been trying multiple combinations of ffmpeg args. To answer the other question, we have video files that have multiple streams, usually with single channels. I'll post some cmdline examples shortly.

This cmdline example kind of does what I want; there are 8 streams, and I'm able to combine all audio into one. THe issue is having to know the number before running ffmpeg:

ffmpeg -i EXAMPLE.MOV -filter_complex "[0:v]scale=-2:720,format=yuv420p[v];[0:a]amerge=inputs=8[a]" -map "[v]" -map "[a]" -c:v libx264 -crf 23 -preset medium -c:a libmp3lame -ar 44100 -ac 2 OUTPUT.mov
like image 415
wkimbrough Avatar asked Aug 22 '17 17:08

wkimbrough


People also ask

How do I combine audio and video in FFmpeg?

Using the “concat” Filter[0:0][0:1] and [1:0][1:1] tell FFmpeg to take video stream #0 and audio stream #1 from the first input video and second input video respectively. n=2 sets the number of segments, which is equivalent to the number of input videos.


2 Answers

You can use ffprobe to find the number of audio streams and use the output as a variable in your ffmpeg command. Bash example using wc to count the audio streams listed by ffprobe:

ffmpeg -i input.mov -filter_complex "[0:v]scale=-2:720,format=yuv420p[v];[0:a]amerge=inputs=$(ffprobe -loglevel error -select_streams a -show_entries stream=codec_type -of csv=p=0 input.mov | wc -l)[a]" -map "[v]" -map "[a]" -c:v libx264 -crf 23 -preset medium -c:a libmp3lame -ar 44100 -ac 2 output.mov
like image 179
llogan Avatar answered Oct 12 '22 05:10

llogan


The following command should do the same thing as llogan's answer but doesn't recompress the video track and requires you to identify how many audio tracks should be merged together.

If you want to know how many audio streams are present, try:

ffprobe originalfile.mov 2>&1 | grep 'Stream #'

Once you have identified how many audio streams should be merged, use that number in the amerge=inputs=2 parameter here. This command will merge the streams into one and recompress the audio using aac compression.

ffmpeg -i originalfile.mov -c:v copy -c:a aac -b:a 160k -ac 2 -filter_complex amerge=inputs=2 output.mp4
like image 20
ScottKu Avatar answered Oct 12 '22 05:10

ScottKu