Skip to content

Commit 6073f6c

Browse files
committed
Add more listeners for m3u8 hls files
1 parent 7068ffe commit 6073f6c

File tree

1 file changed

+31
-9
lines changed

1 file changed

+31
-9
lines changed

dotcom-rendering/src/lib/useSubtitles.ts

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,19 +26,41 @@ export const useSubtitles = ({
2626
useEffect(() => {
2727
if (!video) return;
2828

29-
const textTracks = video.textTracks;
29+
const tracks = video.textTracks;
3030

31-
const setTrackFromList = () => {
32-
const track = textTracks[0];
33-
// We currently only support one text track per video, so we are ok to access [0] here. If we add additional languages, this will need updating.
34-
if (!track) return;
31+
const pickTrack = () => {
32+
// choose the right one if you have labels/languages
33+
const t =
34+
Array.from(tracks).find((tt) => tt.kind === 'subtitles') ||
35+
tracks[0];
3536

36-
setActiveTrack(track);
37+
if (!t) return;
38+
39+
// make THIS track load cues
40+
t.mode = 'hidden';
41+
// disable others so the UA doesn't switch on you
42+
for (const other of Array.from(tracks)) {
43+
if (other !== t) other.mode = 'disabled';
44+
}
45+
46+
setActiveTrack(t);
3747
};
3848

39-
//Get Text track as soon as the video element is available.
40-
setTrackFromList();
41-
// TODO:: are there changes we need to listen for that might change the text track?
49+
// 1) pick immediately if already present
50+
pickTrack();
51+
52+
// 2) react when HLS adds tracks later (common on mobile)
53+
const onAdd = () => pickTrack();
54+
tracks.addEventListener('addtrack', onAdd);
55+
56+
// 3) also after metadata (some browsers populate then)
57+
const onMeta = () => pickTrack();
58+
video.addEventListener('loadedmetadata', onMeta);
59+
60+
return () => {
61+
tracks.removeEventListener('addtrack', onAdd);
62+
video.removeEventListener('loadedmetadata', onMeta);
63+
};
4264
}, [video]);
4365

4466
useEffect(() => {

0 commit comments

Comments
 (0)