繁体   English   中英

在PHP中读取WebVTT文件

[英]Reading WebVTT files in PHP

有没有人有使用PHP读取WebVTT(.vtt)文件的经验?

我正在使用CakePHP开发一个应用程序,在其中我需要阅读一堆vtt文件并获取开始时间和相关文本。

因此,以文件为例:

00:00.999 --> 00:04.999
sentence one

00:04.999 --> 00:07.999
sentence two

00:07.999 --> 00:10.999
third sentence
with a line break

00:10.999 --> 00:14.999
a fourth sentence
on three
lines

我需要能够提取如下内容:

00:00.999 sentence one
00:04.999 sentence two
00:07.999 third sentence with a line break
00:10.999 a fourth sentence on three lines

请注意,可能会有换行符,因此每个时间戳之间没有设定的行数。

我的计划是搜索“->”,这是每个时间戳之间的通用字符串。 有谁知道如何最好地实现这一目标?

这似乎实现了我所需要的,即输出开始时间和任何后续的文本行。 我使用的文件很小,因此使用PHP的file()函数将所有内容读取到数组中似乎还可以; 不确定这是否适用于大文件。

    $file = 'test.vtt'; 
    $file_as_array = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    foreach ($file_as_array as $f) {    

        // Find lines containing "-->"  
        $start_time = false;
        if (preg_match("/^(\d{2}:[\d\.]+) --> \d{2}:[\d\.]+$/", $f, $match)) {              
            $start_time = explode('-->', $f);
            $start_time = $start_time[0];
            echo '<br>';
            echo $start_time;
        }

        // It's a line of the file that doesn't include a timestamp, so it's caption text. Ignore header of file which includes the word 'WEBVTT'
        if (!$start_time && (!strpos($f, 'WEBVTT')) ) {             
            echo ' ' . $f . ' ';
        }   

    }       
}

您可以执行以下操作:

<?PHP

function send_reformatted($vtt_file){
 // Add these headers to ease saving the output as text file
    header("Content-type: text/plain");
    header('Content-Disposition: inline; filename="'.$vtt_file.'.txt"');

    $f = fopen($vtt_file, "r");
    $line_new = "";

    while($line = fgets($f)){
        if (preg_match("/^(\d{2}:[\d\.]+) --> \d{2}:[\d\.]+$/", $line, $match)) {
            if($line_new) echo $line_new."\n";
            $line_new = $match[1];
        } else{
            $line = trim($line);
            if($line) $line_new .= " $line";
        }
    }

    echo $line_new."\n";
    fclose($f);
}


send_reformatted("test.vtt");

?>

要解析文件,您可以使用如下库:

$subtitles = Subtitles::load('subtitles.vtt');
$blocks = $subtitles->getInternalFormat(); // array

foreach ($blocks as $block) {
    echo $block['start'];
    echo $block['end'];
    foreach ($block['lines'] as $line) {
        echo $line;
    }
} 

https://github.com/mantas-done/subtitles

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM