kraftydevil
kraftydevil

Reputation: 5246

Use ffmpeg to sequentially add multiple audio tracks and pin a specific track to the end

I have a single video with no audio tracks and want to add several audio tracks sequentially (each track starts immediately after the other).

The basic case might look something like this:

|-----------VIDEO-----------VIDEO-------------VIDEO-----------VIDEO-----------|  
|---FULL AUDIO TRACK 1---|---FULL AUDIO TRACK 2---|---PARTIAL AUDIO TRACK 3---|

Here is my attempt to achieve this:

ffmpeg -i video.mov -i audio1.mp3 -i audio2.mp3 -i audio3.mp3 -map 0:0 -map 1:0 -map 2:0 -map 3:0 out.mp4

Of course it doesn't produced the desired result. It only uses the first music clip in out.mp4, and no other audio tracks are started when it ends.

Question 1
What am I missing in order to add multiple audio tracks sequentially? I assume it's specifying starting and end points of audio clips but I'm coming up short on locating the syntax.

...

In addition, I'm looking for a way to ensure that the video ends with the full duration of AUDIO TRACK 3, as seen below:

|-----------VIDEO-----------VIDEO-------------VIDEO-----------VIDEO-----------|  
|---FULL AUDIO TRACK 1---|---PARTIAL AUDIO TRACK 2---|---FULL AUDIO TRACK 3---|

In this case, AUDIO TRACK 2 gets trimmed so that the full AUDIO TRACK 3 is pinned to the end.

Question 2
Can this type of audio pinning be done in FFmpeg, or would I have to trim AUDIO TRACK 2 with another program first?

Upvotes: 0

Views: 3252

Answers (1)

llogan
llogan

Reputation: 133743

Use the atrim, asetpts, and concat filters:

ffmpeg -i video.mov -i audio1.mp3 -i audio2.mp3 -i audio3.mp3
  -filter_complex "[2:a]atrim=duration=5,asetpts=PTS-STARTPTS[a2];[1:a][a2][3:a]concat=n=3:a=1:v=0[a]"
  -map 0:v -map "[a]" -c copy -c:a aac -shortest output.mp4
  • atrim trims the audio. You can also use the start and/or end options if you prefer them over duration.
  • asetpts resets the timestamps (required by concat).
  • concat concatenates each audio segment.

If you want to automate this you'll have to script it. You can get the duration of each input with ffprobe:

ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 input.mp4

Then use that to determine the duration of whatever audio stream you want to trim.

Upvotes: 4

Related Questions