WebVTT - 为 video 和 audio 添加字幕
WebVTT
想给 <video>
挂上字幕,看了一下有原生的方案来实现这个。Web 视频文本轨道格式(WebVTT)是一种使用 <track>
元素显示定时文本轨道(如字幕或标题)的格式。
WebVTT - Web Video Text Tracks
Web Video Text Tracks Format (WebVTT) is a format for displaying timed text tracks (such as subtitles or captions) using the
<track>
element. The primary purpose of WebVTT files is to add text overlays to a<video>
. WebVTT is a text based format, which must be encoded using UTF-8. Where you can use spaces you can also use tabs. There is also a small API available to represent and manage these tracks and the data needed to perform the playback of the text at the correct times.
不过有意思的是,除了最上面的 WEBVTT
,WebVTT 的格式与 .srt 几乎完全一样。
WEBVTT
00:01.000 --> 00:04.000
Never drink liquid nitrogen.
00:05.000 --> 00:09.000
- It will perforate your stomach.
- You could die.
为 <video>
添加 <track>
只要给 video 增加 track 元素,指明 .vtt 文件的路径,kind 为 subtitles 就可以正常显示字幕。可以通过多个 track 来加载不同 srclang 和 kind 的 .vtt 文件。
<video src="video.mp4">
<track src="music.vtt" kind="subtitles" default />
</video>
具体的内容细节不做赘述,值得一提的是,WebVTT 的样式可以通过 CSS 来控制,这点真好。其它细节可以看 Web Video Text Tracks Format (WebVTT) - Web APIs | MDN
<audio>
怎么办?
目前浏览器并不支持通过 track 为 audio 添加类似的字幕,但我就是想显示一些歌词怎么办?可以考虑用 video 标签来播放 audio 文件,为 source 指定 type = audio/* 并不影响 video 本身的功能,字幕依然可以正常工作。
<video autoplay width="720" poster="poster.png">
<source src="music.mp3" type="audio/mp3" />
<track src="music.vtt" kind="subtitles" default />
</video>
比如这段视频(因为是录屏所以没有声音,不过可以看到字幕在切换),那个硕大的音乐图标是我给 video 加的 poster,去掉的话 video 完全透明。
