Search code examples
javascriptvideo.js

How to reload vtt subtitles tracks in VideoJs?


I generate the videojs html5 video player with default vtt tracks, the editor edits them manually and clicks save, now you have new vtt file, that has the exact file name and path of the old file, it's just that videojs keeps reading the old file. The vtt file is hosted on the server.

<video id="player">  
     <source type="video/mp4" src="/my_video_file.mp4">   
     <track src="/captions_file.vtt" label="English" kind="captions" srclang="en" default>
</video>

if I do player.reset(), it messes up the player, I can't even override the current player, if I do player.dispose() the entire div is deleted. What to do in this case?

I also tried addRemoteTextTrack and remoteTextTracks as well, and it didn't work, the player kept playing fine, and the tracks were removed but I don't see the new tracks after adding them

const switchTracks = (vttFile, api_key, lang_code, language) => {
  // generate random number to avoid caching
  const random = Math.floor(Math.random() * 1000000);

  // remove all existing tracks
  console.log("removing vtt:", vttFile);
  let tracks = player.remoteTextTracks();
  let numTracks = tracks.length;
  for (let i = numTracks - 1; i >= 0; i--) {
    player.removeRemoteTextTrack(tracks[i]);
  }

  console.log("adding vtt:", vttFile);
  player.addRemoteTextTrack(
    {
      src: `${vttFile}?api_key=${api_key}&random=${random}`,
      kind: "subtitles",
      srclang: lang_code,
      label: language,
    },
    false
  );
};

Should I reload the player somehow or do something else? I get no javascript or python errors, I know the function is working fine, I don't know why the subtitles aren't showing.

I also asked the question on github and a maintainer is trying to help me, I posted here as well maybe you know a possible way to address the problem


Solution

  • I had to add mode: "showing", I'll accept my answer in 2 days.

    const switchTracks = (vttFile, api_key, lang_code, language) => {
      // generate random number to avoid caching
      const random = Math.floor(Math.random() * 1000000);
    
      // remove all existing tracks
      console.log("removing vtt:", vttFile);
      let tracks = player.remoteTextTracks();
      let numTracks = tracks.length;
      for (let i = numTracks - 1; i >= 0; i--) {
        player.removeRemoteTextTrack(tracks[i]);
      }
    
      console.log("adding vtt:", vttFile);
      player.addRemoteTextTrack(
        {
          src: `${vttFile}?api_key=${api_key}&random=${random}`,
          kind: "subtitles",
          srclang: lang_code,
          label: language,
          mode: "showing",
        },
        false
      );
    };