Skip to content

Instantly share code, notes, and snippets.

@frdnrdb
Last active January 4, 2023 15:12
Show Gist options
  • Save frdnrdb/de91a652adc2bbb8c60fd3b5d7977bd3 to your computer and use it in GitHub Desktop.
Save frdnrdb/de91a652adc2bbb8c60fd3b5d7977bd3 to your computer and use it in GitHub Desktop.
Programmatically assigning text track video captions from vtt file url
const vttText = await fetch(vttUrl).then(res => res.text());
const timeCodeToSeconds = (str) => {
const [h, m, s] = str.split(':').map(Number);
return h * 60 * 60 + m * 60 + s;
};
// PS! simple TEST parser! vtt format could contain NOTES and css styling
// https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
const cues = vttText
.split(/^\d{1,}$/gm)
.slice(1)
.map((str) => str.trim())
.map((str) => {
const splitIndex = str.indexOf('\n');
const [from, to] = str.substring(0, splitIndex).split(/\s[^\d]+/);
const text = str.substring(splitIndex + 1);
return [timeCodeToSeconds(from), timeCodeToSeconds(to), text];
});
const track = video.addTextTrack('captions', 'Captions', 'no');
cues.forEach((args) => track.addCue(new VTTCue(...args)));
track.mode = 'showing';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment