First you'll want to bring your input format into a processable format, something along the lines of
var subtitles = [
{
start: 0.21,
end: 0.3,
text: "Subtitle Text 1"
},
{
start: 0.32,
end: 0.52,
text: "Subtitle Text 2"
}
];
Note that I chose "end" instead of "duration" here, because "duration" in my eyes would mean that the subtitle ends at start + duration (0.21 + 0.3 = 0.51) seconds.
The formatting function was almost correct, but needed the input value supplied as milliseconds instead of decimal second values. For output, you also need to pad hours/minuts/seconds with zeroes. You'd better use a helper function for this where you can specify the target string length, but for this example I just did it inline:
var subtitles = [
{
start: 0.21,
end: 0.3,
text: "Subtitle Text 1"
},
{
start: 0.32,
end: 0.52,
text: "Subtitle Text 2"
}
],
srtCount = 0;
function srtTimestamp(seconds) {
var $milliseconds = seconds*1000;
$seconds = Math.floor($milliseconds / 1000);
$minutes = Math.floor($seconds / 60);
$hours = Math.floor($minutes / 60);
$milliseconds = $milliseconds % 1000;
$seconds = $seconds % 60;
$minutes = $minutes % 60;
return ($hours < 10 ? '0' : '') + $hours + ':'
+ ($minutes < 10 ? '0' : '') + $minutes + ':'
+ ($seconds < 10 ? '0' : '') + $seconds + ','
+ ($milliseconds < 100 ? '0' : '') + ($milliseconds < 10 ? '0' : '') + $milliseconds;
}
function inputToSRT(sub_in) {
return ++srtCount + "\r\n" + srtTimestamp(sub_in.start) + " --> " + srtTimestamp(sub_in.end) + "\r\n" + sub_in.text + "\r\n\r\n";
}
for (var i=0; i<subtitles.length; i++) {
console.log(inputToSRT(subtitles[i]));
}