4

How to change the source files of subtitles on the fly (originally defined in the HTML via <track> element) when changing a video source (via the setSrc() method) ?

In other words, when playing a video I use setSrc() method to change video source and I would also redefine the subtitle files (SRT) linked.

glennsl
  • 28,186
  • 12
  • 57
  • 75
srcmax
  • 63
  • 1
  • 5

3 Answers3

6

A trick I devised was to set an ID on the subtitle track

<track id="subtitles" kind="subtitles" src="subtitles.srt" srclang="en" />

Then inside of whatever event you need you can use:

$('#subtitles').attr('src', 'different_subtitles.srt');
player.findTracks();
player.loadTrack(0);
player.setSrc('different_video.mp4');

There may be a more elegant way to go about this and MediaElementJS really should provide an API for this. But in the meantime this trick should get you by.

tuxracer
  • 201
  • 2
  • 5
2

This doesn't quite work for every event (like 'ended'). While this code does reliably load & change the TRACK source, if you have a language already displaying, it will not display the newly 'sourced' TRACK with a new video unless the CC is set to None and then a language.

Craig B
  • 21
  • 2
  • As mentioned by CraigB, you need to set the tracks to none and then load the language you want again. Adding player.setTrack('none'); and player.setTrack('en'); after findTracks() loadTrack(0) works fine. – am_ Oct 25 '15 at 13:13
2

Another approach is to remove the whole video element and replace it with a new video element with all its new track elements.

You can achieve this by replacing the innerHTML of the video's parent element:

document.getElementById('videoparent').innerHTML='<video src="url-to-my-video.mp4" controls=""><track src="url-to-my-subtitle.vtt" default="" srclang="de" label="My subtitle"></video>';

Works fine at least in Firefox 87 and Chromium 89.