Created
December 23, 2017 10:21
-
-
Save pfrenssen/064b75e4a2f888f23e0c11ec5a54fcdc to your computer and use it in GitHub Desktop.
Extract SRT subtitles from MKV files
This file contains 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
#!/usr/bin/env php | |
<?php | |
declare(strict_types = 1); | |
if (count($argv) !== 2) help(); | |
$dirname = $argv[1]; | |
if (!is_dir($dirname)) help(); | |
$directory_path = realpath($dirname); | |
$dir = new DirectoryIterator($directory_path); | |
foreach ($dir as $file) { | |
if (!$file->isDot() && $file->isFile()) { | |
$filename = $file->getFilename(); | |
$path = $file->getPathname(); | |
if (substr($filename, -4) === '.mkv') { | |
foreach (subtitle_tracks($path) as $track) { | |
extract_subtitles($path, $track); | |
} | |
} | |
} | |
} | |
function subtitle_tracks(string $path): array { | |
$tracks = []; | |
$output = `mkvmerge -i {$path} | grep subtitles`; | |
foreach (explode(PHP_EOL, $output) as $line) { | |
if (preg_match('/Track ID (\d+): subtitles \(SubRip\/SRT\)/', $line, $matches)) { | |
$tracks[] = (int) $matches[1]; | |
} | |
} | |
return $tracks; | |
} | |
function extract_subtitles(string $path, int $track): void { | |
$subtitle_path = preg_replace('/.mkv$/', ".$track.srt", $path); | |
if (is_file($subtitle_path)) { | |
print "File $subtitle_path exists. Skipping.\n"; | |
return; | |
} | |
passthru("mkvextract tracks {$path} {$track}:{$subtitle_path}"); | |
} | |
function help(): void { | |
print "Usage: ./extract-subtitles.php <dir>\n"; | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment