从视频中删除TextTrack

时间:2015-03-27 17:43:36

标签: javascript html5 html5-video media-source mpeg-dash

有没有一种方法可以删除通过JavaScript添加到HTML5 <video>标记的单个TextTrack?以下代码是如何添加曲目的简单演示,但我还没有找到一个删除曲目的好方法:

document.querySelector('video#myVideo').addTextTrack(...);

3 个答案:

答案 0 :(得分:2)

没有机制可以删除添加的文本轨道(可能是当前规范中的一个缺陷(?)。还有一个onremovetrack事件但是......)。

我们唯一能做的就是禁用或隐藏它。确保您保留对曲目的引用:

var video = document.querySelector('video#myVideo');
var track = video.addTextTrack("...");
...
track.mode = "showing";  // when cues are added and is ready

然后当你不再需要它时:

track.mode = "disabled"; // or "hidden"

(你也可以绕过重置src,但我还没有尝试过这个......)

答案 1 :(得分:0)

TextTrackList的实现

如果您未阅读,请先参考此URL。 https://developer.mozilla.org/en-US/docs/Web/API/TextTrackList

它提到了

  

onremovetrack   发送removetrack事件时调用的事件处理程序,指示已从media元素中删除了文本轨道。

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控制台输出

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

以上引用表示视频DOM元素删除后,将触发onremovetrack。看到这个例子。

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, …}

删除曲目

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++;
}

禁用跟踪

videoElement.textTracks[0].mode = "disabled"; // Disable English
videoElement.textTracks[1].mode = "showing";  // Enable Deutsche

答案 2 :(得分:0)

我使用javascript解决了此问题(经过测试的作品包含1条或更多曲目):

使用某种选择器在DOM中获取媒体播放器对象,然后获取其所有轨道,然后以相反的顺序遍历数组来逐个删除它们。

var player = videojs(document.getElementById(playerId));
var tracks = player.remoteTextTracks();
var numTracks = tracks.length;
for(var i = numTracks - 1; i >=0 ; i--) {
    player.removeRemoteTextTrack(tracks[i]);
}