Skip to content

Instantly share code, notes, and snippets.

@javatask
Created October 24, 2019 13:17
Show Gist options
  • Save javatask/dc195cc6ad25f859dcd54f1e8aa1e235 to your computer and use it in GitHub Desktop.
Save javatask/dc195cc6ad25f859dcd54f1e8aa1e235 to your computer and use it in GitHub Desktop.
Convert Google speech to text JSON into SRT
const text = require("./text.json");
function toHHMMSS(seconds) {
var sec_num = parseInt(seconds, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - hours * 3600) / 60);
var seconds = sec_num - hours * 3600 - minutes * 60;
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
return hours + ":" + minutes + ":" + seconds;
}
let i = 1;
let aggregatedFrom = 0;
function processPart(res) {
const arr = res.alternatives[0].words;
let srt = "";
let words = "";
arr.forEach(({ startTime, endTime, word }) => {
let to = parseInt(endTime.split(".")[0]);
words += ` ${word}`;
if (to - aggregatedFrom > 3) {
srt += `${i++}\n`;
srt += `${toHHMMSS(aggregatedFrom)} --> ${toHHMMSS(to)}\n`;
srt += `${words}\n`;
srt += `\n`;
words = "";
aggregatedFrom = to;
}
});
return srt;
}
const parts = text.response.results.map(part => {
return processPart(part);
});
let file = parts.reduce((agg, p) => `${agg}${p}`);
console.log(file);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment