-
Notifications
You must be signed in to change notification settings - Fork 18
/
setup-audio-tracks.js
96 lines (77 loc) · 2.71 KB
/
setup-audio-tracks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import videojs from 'video.js';
/**
* Setup audio tracks. Take the tracks from dash and add the tracks to videojs. Listen for when
* videojs changes tracks and apply that to the dash player because videojs doesn't do this
* natively.
*
* @private
* @param {videojs} tech the videojs player tech instance
* @param {videojs.tech} tech the videojs tech being used
*/
function handleAudioTracksAdded(tech, shakaPlayer, tracks) {
const videojsAudioTracks = tech.audioTracks();
function generateIdFromTrackIndex(index) {
return `dash-audio-${index}`;
}
function generateLabelFromTrack(track) {
let label = track.language;
if (track.role) {
label += ` (${track.role})`;
}
return label;
}
function findDashAudioTrack(subDashAudioTracks, videojsAudioTrack) {
return subDashAudioTracks.find((track) =>
generateLabelFromTrack(track) === videojsAudioTrack.label
);
}
// Safari creates a single native `AudioTrack` (not `videojs.AudioTrack`) when loading. Clear all
// automatically generated audio tracks so we can create them all ourself.
if (videojsAudioTracks.length) {
tech.clearTracks(['audio']);
}
const currentAudioTrack = tracks[0];
tracks.forEach((dashTrack, index) => {
const label = generateLabelFromTrack(dashTrack);
if (dashTrack === currentAudioTrack) {
tech.trigger('shakaaudiotrackchange', {
language: dashTrack.language
});
}
// Add the track to the player's audio track list.
videojsAudioTracks.addTrack(
new videojs.AudioTrack({
enabled: dashTrack === currentAudioTrack,
id: generateIdFromTrackIndex(index),
kind: 'main',
label,
language: dashTrack.language
})
);
});
const audioTracksChangeHandler = () => {
for (let i = 0; i < videojsAudioTracks.length; i++) {
const track = videojsAudioTracks[i];
if (track.enabled) {
// Find the audio track we just selected by the id
const dashAudioTrack = findDashAudioTrack(tracks, track);
if (dashAudioTrack) {
// Set is as the current track
tech.trigger('shakaaudiotrackchange', {
language: dashAudioTrack.language
});
shakaPlayer.selectAudioLanguage(dashAudioTrack.language, dashAudioTrack.role);
// Stop looping
continue;
}
}
}
};
videojsAudioTracks.addEventListener('change', audioTracksChangeHandler);
shakaPlayer.addEventListener('unloading', () => {
videojsAudioTracks.removeEventListener('change', audioTracksChangeHandler);
});
}
export default function setupAudioTracks(tech, shakaPlayer) {
handleAudioTracksAdded(tech, shakaPlayer, shakaPlayer.getAudioLanguagesAndRoles());
}