Sub topic 9
Adding captions and subtitles with track
This chapter assumes you can write basic HTML and CSS, and that you can use JavaScript event listeners. It also assumes you have already embedded a video element with controls, and know what a source element does. By the end you will be able to add captions and subtitles with the track element, write a WebVTT file, and handle the common errors.
Captions, subtitles, and what the track element does
Captions and subtitles are both timed text shown over video, but they serve different readers.
- Subtitles translate or transcribe the speech for viewers who can hear the audio but do not understand the language.
- Captions include the speech plus other meaningful sound, such as
[door slams]or[tense music]. They are written for viewers who cannot hear the audio.
The track element attaches a timed text file to a video or audio element. It is a void element, so it has no closing tag. You place it inside the media element, usually after the source elements.
<video controls width="640" poster="poster.jpg" preload="metadata">
<source src="clip.webm" type="video/webm">
<source src="clip.mp4" type="video/mp4">
<track kind="captions" src="clip.en.vtt" srclang="en" label="English" default>
<p>Your browser cannot play this video. <a href="clip.mp4">Download it instead</a>.</p>
</video>The browser fetches the text file and shows the cues in sync with playback. With controls present, most browsers add a captions menu to the player automatically.
The track attributes
| Attribute | Purpose |
|---|---|
| `src` | URL of the WebVTT file. Required. |
| `kind` | The type of text: `subtitles`, `captions`, `descriptions`, `chapters`, or `metadata`. The default is `subtitles`. |
| `srclang` | Language of the text, as a BCP 47 tag such as `en` or `pt-BR`. Required when `kind` is `subtitles`. |
| `label` | The title shown in the player's track menu. |
| `default` | Marks the track to enable if the user has not chosen another one. |
Choosing a kind
subtitlesis a translation or transcription of dialogue. It is the default if you omitkind.captionsincludes sound effects and speaker cues. Use it for accessibility.descriptionsis text describing the visuals, meant to be read by a screen reader or speech synthesizer.chaptersprovides titles for sections of the media, used for navigation.metadatais for scripts only. The browser never displays it.
Only subtitles, captions, and descriptions are rendered as visible text by default. Browser support for descriptions and chapters varies, so test before you rely on either.
Offering several languages
Add one track element per language. Give each a distinct label and srclang. Mark at most one as default.
<video controls width="640">
<source src="clip.mp4" type="video/mp4">
<track kind="captions" src="clip.en.vtt" srclang="en" label="English captions" default>
<track kind="subtitles" src="clip.es.vtt" srclang="es" label="Español">
<track kind="subtitles" src="clip.fr.vtt" srclang="fr" label="Français">
</video>If more than one track has default, the browser uses the first one. Browsers may also pick a track that matches the user's language settings or accessibility preferences, so default is a hint and not a guarantee.
Writing a WebVTT file
WebVTT (Web Video Text Tracks) is the text format that track loads. The file starts with the line WEBVTT, then a blank line, then cues. Each cue has a time range and the text to show.
WEBVTT
00:00:00.000 --> 00:00:03.500
Welcome to the tutorial.
00:00:03.500 --> 00:00:07.000
First, we will add a video element.Rules that cause most mistakes:
- The first line must be
WEBVTT. Without it the file is rejected. - Timestamps use
HH:MM:SS.mmm. The hours may be omitted (MM:SS.mmm), but the decimal separator is a period, not the comma used by SRT files. - Cues are separated by a blank line.
- A cue's start time must be earlier than its end time.
- The file must be saved as UTF-8.
Optional cue features
A cue can have an identifier on the line above the timestamps. You can also add settings after the end time to control placement, and simple inline markup.
WEBVTT
intro
00:00:00.000 --> 00:00:03.500 line:85% align:center
<v Maya>Welcome to the tutorial.</v>
00:00:03.500 --> 00:00:07.000
[upbeat music]
00:00:07.000 --> 00:00:10.000
First, we will add a <i>video</i> element.<v Maya>is a voice tag that names the speaker.<i>,<b>, and<u>give italic, bold, and underline.line:85%andalign:centerposition the cue.
You can also add NOTE blocks for comments that are not displayed.
How the browser loads and enables tracks
Each track element has a track property (a TextTrack object) with a mode:
disabled: the track is not active, and the browser may not even download it.hidden: the track is active and its cues fire events, but nothing is drawn.showing: the track is active and the cues are displayed.
The following diagram shows the transitions.
You can change the mode from script. This example turns on the first captions track and logs each cue as it appears.
const video = document.querySelector('video');
const track = video.textTracks[0];
track.mode = 'showing';
track.addEventListener('cuechange', () => {
const active = Array.from(track.activeCues || []);
console.log(active.map((cue) => cue.text));
});Setting mode = 'hidden' is useful when you want to read cues, for example to build a clickable transcript, but draw them in your own markup.
Styling cues
The ::cue pseudo-element styles the text of cues on the media element.
video::cue {
background: rgb(0 0 0 / 0.75);
color: #fff;
font-size: 1.1rem;
}Only a limited set of properties works on ::cue, including color, background, font properties, and text shadow. Layout properties such as margin and padding do not apply. Browsers also let users override caption appearance in system settings, and those preferences usually take precedence.
Common errors
- Captions do not appear and the console shows a network error. The path in
srcis wrong, or the server returned an error. Open the VTT URL directly in the browser to check. - The file loads but nothing shows. Check that the first line is exactly
WEBVTT, that timestamps use periods, and that the file is UTF-8. Also check thatmodeis notdisabled. - The track works locally but fails when the VTT is on another domain. Track files fetched from another origin require CORS headers, and the media element needs the
crossoriginattribute. Cross-origin media is covered in a later chapter. - A
file://page fails to load tracks. Browsers block this in many cases. Serve the page from a local web server. - The server sends the wrong type. VTT files should be served as
text/vtt. A server that returns a generic type can cause some browsers to refuse the file. - Two tracks fight over
default. Mark one only. - Captions disappear in fullscreen on custom players. Native fullscreen on the
videoelement keeps the cues. If you make a wrapper element fullscreen instead, the browser's cue rendering is still bound to the video, but your own controls must be inside that wrapper. Test this on the browsers you support.
Accessibility notes
Captions are a core accessibility requirement for prerecorded video with speech, and are covered by WCAG success criterion 1.2.2. Use kind="captions" and include non-speech sounds. For audio-only content such as a podcast, a text transcript on the page is the usual alternative, since track on audio has no visible area to draw cues in. Always provide a label so users can tell tracks apart in the menu.
Exercise
A page has a video with one track kind="subtitles" src="talk.vtt" element, and no captions appear. The VTT file begins with a blank line, then 00:00:01,000 --> 00:00:04,000. Name two problems and give the fix for each.
Show answer
The file is missing the WEBVTT header line, and the timestamp uses a comma as the decimal separator, which is SRT syntax. Add WEBVTT as the first line followed by a blank line, and write the time as 00:00:01.000 --> 00:00:04.000. Also, because kind="subtitles" needs a srclang, add one such as srclang="en", and use kind="captions" if the file includes sound descriptions.
Exercise
You want to read cue text from a track in JavaScript to build a transcript, but you do not want the browser to draw the cues on the video. Which mode do you set, and which event tells you a cue became active?
Show answer
Set track.mode = 'hidden'. Listen for the cuechange event on the TextTrack and read track.activeCues.