Scenario 3: Using cue text to show your own styled captions

Back to scenarios menu

Description

This sample uses the cuechange event on a TextTrack object to let the app know when a new TextTrackCue is ready. When the event is fired, the activeCues property returns a list of current TextTrackCue objects.

While there can be more than one active cue if overlapping times are used in a timed text file, this sample only shows the first cue. The <div> element is styled to show how you can control the way your captions are displayed. The text track is set to kind = "metadata" which will never display in the video player. You can also use the mode value of HIDDEN to suppress the captions so they aren't displayed. If you have multiple language tracks, you can use the mode value to switch between the tracks.

Code

/* CSS */
#display
{
   display:block;
   width:640px;
   height:100px;
   color:Blue;
   background-color:#e7f1fd;
   border-radius:20px;
   border: 1px solid blue;
   text-align:center;
   font-size:18pt;
   font-weight:bold;
          }
           
           
   // Script

   // don't run this until all DOM content is loaded 
   document.addEventListener("DOMContentLoaded", function () 
   {
     var track = document.getElementById("track1");
     track.addEventListener("cuechange", function () 
     {
       var myTrack = this.track;             // track element is "this" 
       var myCues = myTrack.activeCues;      // activeCues is an array of current cues.                                                    
       if (myCues.length > 0) 
       {
         document.getElementById("display").innerText = myCues[0].text;
       }
     }, false);
   }, false); 


   <!-- HTML -->

   <video id="video1" autoplay controls>
     <source src="Video.mp4" type="video/mp4"/>
     <track id="track1" label="English captions"
       src="entrack.vtt" kind="metadata" srclang="en" default />    
   </video>
           
   <div id="display"></div>

Result