简体   繁体   中英

Subtitle Track HTML5 Element Don't Update in Video

I'm facing a problem, I need to change the subtitles track source dynamically from javascript.

The current behaviour is that no change happens and the old subtitles keeps showing.

This is the html:

<video style="width: 50%;" class="m-5" id="vid" controls>
      <track src="oldPath.vtt" id="subtitleTrack" label="English" kind="subtitles" srclang="en" default />
</video>

This is the Javascript:

let subtitleTrack = document.getElementById("subtitleTrack");

function subtitleEdited(newTrackPath) {
  //....
  subtitleTrack.src = newTrackPath;
  //....
}

I need once the track source changed, the new captions should be loaded to the video directly.

I tried loading the video again and it didn't work by adding video.load() after changing the track source.


Update

After further investigation the problem seems to be because of caching issues. I need the new path to be the same old path ( the path has new updates localy ) But the browser takes his copy from the cache without updating it from the local files. __

Second Update

Thanks for the response of @Terry.

I tried adding versioning to the source, but it retrieves nothing.

Check the response size, The ?v=2 response it empty.网络截图

PS The project is electron project.Anyways, I don't think that it can be part of the problem.

As you have mentioned in your comments (and your updated question), that you are using the exact same track path. That will cause the browser to fetch from the cache instead since the file path has not changed: a good idea will be to simply add a cache-busting query string to the src attribute, so that the browser will ignore the cache:

let subtitleTrack = document.getElementById("subtitleTrack");

function subtitleEdited(newTrackPath) {
  //....
  subtitleTrack.src = newTrackPath + '?t=' + new Date().getTime();
  //....
}

Of course if you're more comfortable with using template literals, this might be more readalbe:

subtitleTrack.src = `${newTrackPath}?t=${new Date().getTime()}`;

I miss understood the problem.

the problem was I was trying to access the subtitle file while other function was editing it. So I added a callback to prevent that.

And also by applying @Terry's answer to add that cache-busting query.

It is working now after applying the above changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM