Combine H.264 MP4 Files and Add Audio via MP4Box and FFMPEG

Some late night fun… Since I can’t sleep… I’ve successfully found a means to combine multiple video files and add audio to a combined video progmatically and documenting my findings, thought I would share…

First I had to install GPAC which contains MP4Box, using it allows to combine the video files pre-existing as we have them now into one single file (1.mp4 and 2.mp4 are video files captured with an AXIS IP Camera in H.264):

MP4Box -cat 1.mp4 -cat 2.mp4 out.mp4

Next we determine the length in seconds of the video, this is where a custom PHP Script is involved that will determine the length:

$output = shell_exec("/usr/local/bin/ffmpeg -i {$path}");
preg_match('/Duration: ([0-9]{2}):([0-9]{2}):([^ ,])+/', $output, $matches);
$time = str_replace("Duration: ", "", $matches[0]);
$time_breakdown = explode(":", $time);
$total_seconds = round(($time_breakdown[0]*60*60) + ($time_breakdown[1]*60) + $time_breakdown[2]);

With the example file, here’s what the PHP script would see:

ffmpeg -i out.mp4 2>&1 | grep Duration
Duration: 00:00:13.60, start: 0.000000, bitrate: 875 kb/s

And then we cut the audio file accordingly, the above PHP script returned 14 seconds for our two combined videos, since 13.60 is rounded to 14 from MP4Box, so it starts at 00:00:00 and takes a total time of 14 seconds of the audio file and creates a new file to be used next.

ffmpeg -ss 00:00:00 -t 14 -i music.mp3 final.mp3

Take the combined videos from MP4Box and add the newly created 14 second final.mp3 file and create the final file for viewing.

ffmpeg -vcodec copy -i final.mp3 -i out.mp4 final.mp4

If your wanting to have progressive downloading for web playback:

MP4Box -inter 0.5 final.mp4