Detecting Change in Playing Subtitles Text for 〈video〉Element

javascript
Published on November 30, 2019

Use-Cases of this tutorial

  • Know how to detect when a subtitle text changes for the playing <video>.
  • Know about the cuechange event.

A change in subtitle text of the playing video can be detected by listening to the cuechange event fired on the video's <track> element.

The <track> element is the standard HTML tag to include a subtitle for a <video> element.

<video id="my-video-stream" width="1280" height="720" controls>
    <source src="video.mp4" type="video/mp4">
    <track label="English" kind="subtitles" src="subtitles.vtt" srclang="en" id="en-subtitles-track">
</video>

Sometimes we would like to detect when the subtitles change from one text to another in the playing video.

This can be done in Javascript by listening to the cuechange event on the <track> element.

The cuechange event is fired when the track element has changed the currently shown cues.

What is a cue ? A cue represents a single subtitle block. It can have the following components :

  • Cue identifier (optional). This is followed by a newline.
  • Cue timings.
  • Cue settings (optional). This is followed by a newline.
  • One or multiple newlines
  • Cue content

For example below is a subtitle VTT file having 5 cues.

WEBVTT

1
00:02.170 --> 00:04.136 position:20%,line-left align:right size:45%
Subtitle text 1

2
00:04.136 --> 00:05.597
Subtitle text 2
Line 2

3
00:05.597 --> 00:07.405
Subtitle text 3

4
00:07.405 --> 00:08.803
Subtitle text 4

5
00:08.803 --> 00:11.541
Subtitle text 5

Listening to the cuechange Event

document.querySelector("#en-subtitles-track").addEventListener('cuechange', function(e) {
    var cues = e.target.track.activeCues;

    // holds an array of active cues
    console.log(cues);
});

The target.track.activeCues property of the event object holds an array of active cues. A cue is considered active if the current playing position of the video is between the cues' start and end time.

Note : This event will not be fired if the user has not turned on the option to play the subtitle in the video.

In this Tutorial