Skip to content Skip to sidebar Skip to footer

Add Subtitle Line By Line Dynamically To A Video Element In Javascript

I wanted to know if this is currently possible below is my HTML: I also have an array of Object that has all the captions I need t

Solution 1:

You can create WebVTT files from the browser directly and load them using a blob:// URI.

The syntax for WebVTT is quite strict but also quite simple to grasp.

So if we say that your start and end values do represent seconds in the media we could make a generator this way:

const captions_array = [
  { start: 0, end: 2, message: "hello" }, 
  { start: 3, end: 4, message: "how" }, 
  { start: 5, end: 8, message: "are" }
];
constVTTFile = makeVTT( captions_array );
const vid = document.querySelector( "video" );
const track = document.createElement( "track" );
track.kind = "captions";
track.label = "English";
track.srclang = "en";
track.src = URL.createObjectURL( VTTFile );
vid.addEventListener( "loadedmetadata", (evt) => {
  track.mode = "showing";
  vid.textTracks[0].mode = "showing"; // thanks Firefox 
});
vid.append( track );

functionmakeVTT( array ) {
  const text = array.reduce( (str, { start, end, message }, index) => {
    // you would also have to make a "seconds to timestamp" parser// but I leave it to the reader as an exercisereturn str + `
00:00:${ start.toFixed(3).padStart(6, "0") } --> 00:00:${ end.toFixed(3).padStart(6, "0") }${ message }`;
  }, `WEBVTT`);
  returnnewBlob( [ text ], { type: "text/plain" } );
}
video { max-height: 100vh; max-width: 100vw; }
<videocontrolssrc="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"></video>

Post a Comment for "Add Subtitle Line By Line Dynamically To A Video Element In Javascript"