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>