How to Manipulate MKV Files with FFmpeg

This article provides a practical guide on how to use FFmpeg, a powerful command-line tool, to manipulate MKV (Matroska) video files. You will learn how to perform essential video editing tasks such as converting formats without losing quality, cutting and trimming segments, extracting audio tracks, and re-encoding video codecs using simple, direct commands.

Remuxing MKV to MP4 (Without Re-encoding)

Remuxing changes the container format from MKV to MP4 without altering the underlying video and audio data. Because it does not re-encode the stream, this process is incredibly fast and preserves original quality.

ffmpeg -i input.mkv -c copy output.mp4

Trimming and Cutting MKV Videos

You can cut a specific segment out of an MKV file by defining a start time and duration. Using the copy codec ensures the cut is instantaneous.

ffmpeg -ss 00:01:30 -i input.mkv -to 00:02:45 -c copy output.mkv

Extracting Audio from an MKV File

If you only need the audio track from an MKV file, you can extract it into an audio container.

To extract the original audio stream without re-encoding (e.g., extracting AC3 or AAC audio):

ffmpeg -i input.mkv -vn -c:a copy output.mka

To convert the extracted audio to a highly compatible MP3 file:

ffmpeg -i input.mkv -vn -c:a libmp3lame -q:a 2 output.mp3

Re-encoding Video and Audio Codecs

Sometimes you need to compress an MKV file or convert its codecs for better device compatibility. The command below transcodes the video to H.264 and the audio to AAC.

ffmpeg -i input.mkv -c:v libx264 -crf 23 -c:a aac -b:a 192k output.mkv