5

I have an input like like this:

start: 10 | duration: 1 | text: Subtitle Text 1 
start: 15 | duration: 2 | text: Subtitle Text 2 
start: 20 | duration: 3 | text: Subtitle Text 3

It's a subtitle instruction set, that says following:

At 10 second of the video, show "Subtitle Text 1" for 1 seconds
At 15 second of the video, show "Subtitle Text 2" for 2 seconds
At 20 second of the video, show "Subtitle Text 3" for 3 seconds

This input needs to be converted into SRT format, so it becomes something like this:

1
00:00:10,000 --> 00:00:11,000
Subtitle Text 1

2
00:00:15,000 --> 00:00:17,000
Subtitle Text 2

3
00:00:20,000 --> 00:00:23,000
Subtitle Text 3

Would it be possible for someone to show me how would you go about converting any given seconds value into SRT format (00:00:00,000) by using PHP?

That's all I really need, the rest I can figure out myself.

Thanks, much appreciated.

jjj
  • 2,594
  • 7
  • 36
  • 57

2 Answers2

4
private function seconds2SRT($seconds)
{
    $hours = 0;
    $whole = floor($seconds);
    $fraction = $seconds - $whole;
    $milliseconds = number_format($fraction, 3, '.', ',');
    $milliseconds_array = explode('.', strval($milliseconds));
    $milliseconds = $milliseconds_array[1];

    if ($seconds > 3600) {
        $hours = floor($seconds / 3600);
    }
    $seconds = $seconds % 3600;


    return str_pad($hours, 2, '0', STR_PAD_LEFT)
        . gmdate(':i:s', $seconds)
        . ($milliseconds ? ",$milliseconds" : '');
}
Community
  • 1
  • 1
jjj
  • 2,594
  • 7
  • 36
  • 57
1
function secondsToSrt($seconds)
{
    $parts = explode('.', $seconds); // 1.23
    $whole = $parts[0]; // 1
    $decimal = isset($parts[1]) ? substr($parts[1], 0, 3) : 0; // 23

    $srt_time = gmdate("H:i:s", floor($whole)) . ',' . str_pad($decimal, 3, '0', STR_PAD_RIGHT);

    return $srt_time;
}

Or you can create subtitles like this:

$subtitles = new Subtitles();
$subtitles->add(10, 11, 'Subtitle Text 1');
$subtitles->add(15, 17, 'Subtitle Text 2');
$subtitles->add(20, 23, 'Subtitle Text 3');
echo $subtitles->content('srt');

// or if you need file
$subtitles->save('subtitle-file.srt');

You would need to download this library: https://github.com/mantas-done/subtitles

Mantas D
  • 3,993
  • 3
  • 26
  • 26