Created
July 12, 2012 17:31
-
-
Save azihassan/3099513 to your computer and use it in GitHub Desktop.
Subtitle synchroniser. Goes through the .srt file and edits the hh:mm:ss --> hh:mm:ss as per the user's specificatoins.
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
<?php | |
$begin = microtime(TRUE); | |
$args = parse_argv($argv); | |
echo PHP_EOL.'Processing the file...'.PHP_EOL; | |
$contents = file($args['in'], FILE_IGNORE_NEW_LINES); | |
$difference = $args['diff']; | |
$out = isset($args['out']) ? $args['out'] : $args['in']; | |
$count = 0; | |
foreach($contents as &$line) | |
{ | |
if(strpos($line, '-->') === FALSE) | |
{ | |
continue; | |
} | |
$count++; | |
list($from, $to) = array_map('trim', explode('-->', $line)); | |
$from_time = substr($from, 0, 8); | |
$to_time = substr($to, 0, 8); | |
$synched_from_time = date('H:i:s', strtotime($from_time) + $difference); | |
$synched_to_time = date('H:i:s', strtotime($to_time) + $difference); | |
$line = str_replace(array($from_time, $to_time), array($synched_from_time, $synched_to_time), $line); | |
} | |
file_put_contents($out, implode(PHP_EOL, $contents)); | |
$end = microtime(TRUE); | |
echo 'Subtitle processed successfully, synched '.$count.' lines in '.($end - $begin).' seconds'.PHP_EOL; | |
function parse_argv(array $argv) | |
{ | |
$argc = sizeof($argv); | |
$return = array(); | |
if($argc == 1 || !in_array('--in', $argv) || !in_array('--diff', $argv)) | |
{ | |
printf('Usage : php %s --in in.srt --diff time_in_seconds [-- out out.srt]%s', basename(__FILE__), "\n"); | |
exit; | |
} | |
for($i = 1; $i < $argc; $i += 2) | |
{ | |
list($arg, $val) = array($argv[$i], $argv[$i + 1]); | |
switch($arg) | |
{ | |
case '--in': | |
$return['in'] = $val; | |
break; | |
case '--diff': | |
$return['diff'] = $val; | |
break; | |
case '--out': | |
$return['out'] = $val; | |
break; | |
} | |
} | |
if(!is_readable($return['in'])) | |
{ | |
printf('%s is not readable, aborting...%s', basename($return['in']), PHP_EOL); | |
die; | |
} | |
elseif(isset($return['out'])) | |
{ | |
if(file_exists($return['out']) && !is_writable($return['out'])) | |
{ | |
printf('%s is not writable, aborting...%s', basename($return['out']), PHP_EOL); | |
die; | |
} | |
else | |
{ | |
if(touch($return['out']) === FALSE) | |
{ | |
printf('Failed to create %s, aborting...%s', basename($return['out']), PHP_EOL); | |
die; | |
} | |
} | |
} | |
elseif(!isset($return['out']) && !is_writable($return['in'])) | |
{ | |
printf('%s is not writable, aborting...%s', basename($return['in']), PHP_EOL); | |
die; | |
} | |
return $return; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment