-1

I want to allow the user to upload a subtitles file (e.g. ".srt") to play along an mp4 using plain HTML and JS.

I've tried everything I could think of, but am now out of ideas:

1) Tried setting the src attribute on a track child element of the video element

2) Tried creating a new track element in JS, setting the src attribute, and appending the track as a child of the video element

3) Tried using the HTMLMediaElement.addTextTrack() api of the video element, though the TextTrack api doesn't seem to support a src attribute.

4) Tried all these approaches with all combinations of src, srcObject (though I don't think this property is valid for track elements), and URL.createObjectURL.

const $ = document.querySelector.bind(document);

$('#subtitles-input').addEventListener('change', () => {
  // approach 1
  $('#subtitles').src = URL.createObjectURL($('#subtitles-input').files[0]);

  // approach 2
  let track = document.createElement('track');
  track.kind = 'captions';
  track.label = 'English';
  track.srclang = 'en';
  track.src = URL.createObjectURL($('#subtitles-input').files[0]);
  track.mode = 'showing';
  $('#video').appendChild(track);
});
<lablel>Subtitles: <input id="subtitles-input" type="file"></lablel>

<video id="video" src="http://techslides.com/demos/sample-videos/small.mp4" controls>
 <track id="subtitles" kind="subtitles" label="English captions" srclang="en" default>
</video>
junvar
  • 11,151
  • 2
  • 30
  • 46

1 Answers1

1

Apparently, my problem was using an .srt format instead of a .vtt format.

They're almost identical, adding WEBVTT as the first line and replacing ,'s used to indicate milliseconds with .'s is sufficient to convert a valid srt file to a valid vtt file. Though vtts seem to have additional optional features such as text formatting.

For what it's worth, approaches 1 and 2 worked equally well. Approach 3 and 4 don't work for the same reason mentioned above: TextTrack api doesn't support a src property srcObject is not a valid track element attribute, and src requires URL.createObjectURL(file).

const $ = document.querySelector.bind(document);

$('#subtitles-input').addEventListener('change', () => {
  // approach 1
  $('#subtitles').src = URL.createObjectURL($('#subtitles-input').files[0]);

  // approach 2
  let track = document.createElement('track');
  track.src = URL.createObjectURL($('#subtitles-input').files[0]);
  $('#video').appendChild(track);
});
<lablel>Subtitles: <input id="subtitles-input" type="file"></lablel>

<video id="video" src="http://techslides.com/demos/sample-videos/small.mp4" controls>
 <track id="subtitles" kind="subtitles" label="English captions" srclang="en" default>
</video>
junvar
  • 11,151
  • 2
  • 30
  • 46