问题
Is there a good way to delete a single TextTrack added via JavaScript to a HTML5 <video>
tag? The following code is a simple demo of how to add a track, but I haven't found a good way to remove one:
document.querySelector('video#myVideo').addTextTrack(...);
回答1:
There is no mechanism to remove an added text-track (probably a flaw (?) in the current specification. There is also an onremovetrack
event but...).
The only thing we can do is to disable or hide it. Make sure you keep a reference to the track:
var video = document.querySelector('video#myVideo');
var track = video.addTextTrack("...");
...
track.mode = "showing"; // when cues are added and is ready
Then when you no longer need it:
track.mode = "disabled"; // or "hidden"
(you might get around resetting the src as well, but I haven't tried this..)
回答2:
Implementation of TextTrackList
Please refer to this URL first if you did not read. https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList
It metioned that
onremovetrack An event handler to call when the removetrack event is sent, indicating that a text track has been removed from the media element.
HTML
<video src="foo.ogv">
<track kind="subtitles" label="English subtitles" src="subtitles_en.vtt" srclang="en" default>
</track>
<track kind="subtitles" label="Deutsche Untertitel" src="subtitles_de.vtt" srclang="de">
</track>
</video>
videoElement.textTracks console output
var videoElement = document.querySelector("video");
console.log(videoElement);
//output
TextTrackList {0: TextTrack, 1: TextTrack, length: 2, onchange: null, onaddtrack: null, onremovetrack: null}
0: TextTrack {kind: "subtitles", label: "English subtitles", language: "en", id: "", mode: "showing", …}
1: TextTrack {kind: "subtitles", label: "Deutsche Untertitel", language: "de", id: "", mode: "disabled", …}
length: 2
The above quotation means when Video DOM element removed it will trigger onremovetrack. See this example.
videoElement.textTracks.onremovetrack = function(event){
console.log('DOM removed',event)
}
videoElement.removeChild(videoElement.children[0])
//output
DOM removed TrackEvent {isTrusted: true, track: TextTrack, type: "removetrack", target: TextTrackList, currentTarget: TextTrackList, …}
Remove Track
var videoElement = document.querySelector("video");
videoElement.removeChild(videoElement.children[0]); //remove English subtitle
// you need iterlate videoElement.textTracks and find index according to language
var i =0;
var targetLanguage = "de";
for (let track of videoElement.textTracks){
if(track.language !== targetLanguage){
videoElement.removeChild(videoElement.children[i]);
}
i++;
}
Disable Track
videoElement.textTracks[0].mode = "disabled"; // Disable English
videoElement.textTracks[1].mode = "showing"; // Enable Deutsche
来源:https://stackoverflow.com/questions/29306931/delete-a-texttrack-from-a-video