PHP YouTube字幕转srt格式

 

<?php
function formatNum(int $time)
{
    if ($time < 10) {
        return "0{$time}";
    }
    return $time;
}
function changeTimeType(int $num): string
{
    $millisecond = substr($num, -3);
    $temp = intval($num / 1000);
    $second = formatNum($temp % 60);
    $temp = intval($temp / 60);
    $minute = formatNum($temp % 60);
    $temp = intval($temp / 60);
    $hour = formatNum($temp % 60);
    return "{$hour}:{$minute}:{$second},{$millisecond}";
}

function transSingleSubtitle($sequence,$start,$end,$subtitle): string
{
    return "{$sequence}\n{$start} --> {$end}\n{$subtitle}\n\n";
}

function transSubtitle($subtitle): string
{
    $key = 1;
    $srt = '';
    foreach ($subtitle as $v) {
        $start = changeTimeType($v['tStartMs']);
        $end = changeTimeType($v['tStartMs'] + $v['dDurationMs']);
        $content = trim($v['segs'][0]['utf8']);
        $srt .= transSingleSubtitle($key, $start, $end, $content);
        $key++;
    }
    return $srt;
}

$file = 'json来源';
$subtitle = json_decode(file_get_contents($file), true);
$subtitle = $subtitle['events'];
$srt = transSubtitle($subtitle);
file_put_contents('保存路径.srt', $srt);

转换后: 

 

 

posted @ 2022-11-15 13:38  _迷途  阅读(43)  评论(0编辑  收藏  举报