A browser subtitle track expects WebVTT, not a plain transcript with timestamps pasted above each paragraph. A minimal exporter can be useful when your application already has structured cues and only needs basic text captions.
Disclosure: I develop TokTranscript. This article was generated by an AI agent and its code examples were executed locally. The implementation below is independent of the service.
Define a small input contract
Use tuples containing integer start milliseconds, integer end milliseconds and plain text. Treat markup as unsupported input. The exporter escapes text so a speaker's angle brackets are displayed rather than interpreted as WebVTT cue tags.
from html import escape def vtt_time(value): if not isinstance(value, int) or value < 0: raise ValueError("time must be nonnegative integer milliseconds") hours, remaining = divmod(value, 3600000) minutes, remaining = divmod(remaining, 60000) seconds, millis = divmod(remaining, 1000) return f"{hours:02}:{minutes:02}:{seconds:02}.{millis:03}" def export_vtt(cues): blocks = ["WEBVTT"] previous_start = -1 for start, end, text in cues: if end <= start or start < previous_start: raise ValueError("invalid duration or unsorted cues") safe_text = escape(text.replace("\r\n", "\n").replace("\r", "\n"), quote=False) if not safe_text.strip() or "\n\n" in safe_text: raise ValueError("empty text or blank line inside cue") blocks.append(f"{vtt_time(start)} --> {vtt_time(end)}\n{safe_text}") previous_start = start return "\n\n".join(blocks) + "\n\n" assert vtt_time(3600001) == "01:00:00.001" assert "A < B" in export_vtt([(0, 1000, "A < B")]) Keep the scope narrow
This function does not implement regions, positioning, voice annotations or styled cue markup. It allows overlapping cues, because overlapping speech can be valid, but requires cues to be sorted by start time. Do not pass an existing SRT file to it: parse that file into structured cues first.
Test playback separately
Write UTF-8 output and load it as a subtitle track in the actual player. Verify server delivery as well as file contents: a correct file can still fail when its URL, MIME type or cross-origin configuration is wrong. Check at least one cue containing non-ASCII text and one near an hour boundary.
Formatting tests establish file structure. They cannot establish that the transcript matches the audio or that a caption remains on screen long enough to read.