Skip to content

Instantly share code, notes, and snippets.

@KoStard
Created July 31, 2022 21:54
Show Gist options
  • Save KoStard/43aaa61fe13774f9794bd8e3f24b629a to your computer and use it in GitHub Desktop.
Save KoStard/43aaa61fe13774f9794bd8e3f24b629a to your computer and use it in GitHub Desktop.
Using mkvmerge merge multiple video and audio files in the target directory - useful when working with multiple episodes of the same show
from pathlib import Path
import argparse
import subprocess
parser = argparse.ArgumentParser('Tool to merge list of mkv files with mka files using mkvmerge.\n'\
'The audio files should contain the matching video file name.')
parser.add_argument('input_video_path', help='The path where to find the mkv files')
parser.add_argument('input_audio_path', help='The path where to find the mka files')
parser.add_argument('output_path', help='The path where to save the merged files')
args = parser.parse_args()
input_video_path = Path(args.input_video_path)
input_audio_path = Path(args.input_audio_path)
output_path = Path(args.output_path)
video_paths = input_video_path.glob('*.mkv')
audio_paths = list(input_audio_path.glob(f'*.mka'))
mp = {}
for video in video_paths:
audio_path = list(e for e in audio_paths if video.stem in e.name)
if not audio_path or len(audio_path) >= 2:
raise Exception("Couldn't map to the audio video file: " + video)
mp[video] = audio_path[0]
if not output_path.exists():
print(f"Creating folder {output_path}")
output_path.mkdir()
for video, audio in mp.items():
print(f"Merging {video} with {audio}")
instance_output_path = str((output_path / (video.stem + '.mkv')).absolute())
instance_input_video_path = str(video.absolute())
instance_input_audio_path = str(audio.absolute())
subprocess.run(f"mkvmerge -o '{instance_output_path}' '{instance_input_video_path}' '{instance_input_audio_path}'", shell=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment