In linux (Ububtu), ffmpeg is a very convenient tool for manipulating video files. For example, it is possible to use ffmpeg to extract audio tracks or video streams form a file, and combine them together, using only few lines of code. This approach is fast and reliable.If you haven’t ffmpeg installed in your system, simply type:
sudo apt install ffmpeg
In the following example, we will manipulate and combine two MP4 files. Specifically, the goals are:
- Extract audio from MP4 file #1
- Remove audio from MP4 file #2
- Combine video #2 with audio #1
These operations are performed as follows:
ffmpeg -i file_001.mp4 -vn -c:a copy audio_track.m4a
ffmpeg -i file_002.mp4 -c copy -an video_stream.mp4
ffmpeg -i video_stream.mp4 -i audio_track.m4a -codec copy -shortest newVideo.mp4
The last line of code simply combines together the two files, corresponding to the audio and the video. The original codec of the input files is used, so there is no re-encoding and the operation is performed in no time. the -shortest option instructs ffmpeg to trim the end of the audio track or video stream so that audio and video have the same final length.
If you want to trim the resulting file, you can use ffmpeg once again and specify the -ss (start time) and the -t (duration) parameters. If the start is the beginning of the file, simply omit the -ss parameter.
ffmpeg -i newVideo.mp4 -t 00:10:28.000 -c copy trimVideo.mp4
ffmpeg -i newVideo.mp4 -ss 00:02:40.000 -t 00:00:10.500 -c copy excerptVideo.mp4