Created
August 4, 2022 00:02
-
-
Save MathiasYde/dbe35d17cb91f915ef78cba67e0f297d to your computer and use it in GitHub Desktop.
Python script to extract each track in a .MKV file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# requires ffmpeg-python and click | |
import click | |
import ffmpeg | |
import os.path | |
def extract_track(filepath, track_index, output_path): | |
file = ffmpeg.input(filepath) | |
output = ffmpeg.output(file[f"{track_index}"], output_path) | |
ffmpeg.run(output) | |
@click.command() | |
@click.option("--file", "filepath", type=click.Path(exists=True), required=True) | |
@click.option("--video", "video_format", default="mp4", help="Format to use for video tracks") | |
@click.option("--audio", "audio_format", default="mp3", help="Format to use for audio tracks") | |
@click.option("--format", "filename_formatting", default="{filename} - {title}", help="Filename formatting for output files", required=False) | |
@click.option("--directory", "output_directory", help="Directory to store output files", required=False) | |
def main(filepath: str, video_format: str, audio_format: str, filename_formatting: str, output_directory: str): | |
""" | |
Split a MKV file into each stream to representative files. | |
""" | |
codec_map = { | |
"video": video_format, | |
"audio": audio_format, | |
} | |
directory, filename = os.path.split(filepath) # remove filepath | |
filename, _ = os.path.splitext(filename) # remove extension | |
if output_directory is not None: # override directory if other directory is specified | |
directory = output_directory | |
for stream in ffmpeg.probe(filepath).get("streams", []): | |
index = stream.get("index", None) | |
codec = stream.get("codec_type", None) | |
assert index is not None, "Stream index is None" | |
assert codec in codec_map, f"Unsupported codec {codec}" | |
title = stream.get("tags", {}).get("title", codec) # use codec name if no title | |
extension = codec_map[codec] | |
output_filepath = os.path.join(directory, filename_formatting.format(**{ | |
"filename": filename, | |
"title": title, | |
"index": index, | |
"codec": codec, | |
})) | |
output_filepath += f".{extension}" | |
extract_track(filepath, index, output_filepath) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment