如何在Python的Plotly Dash视频播放器中添加VTT字幕?
在Plotly Dash的DashPlayer中添加VTT字幕的方案
DashPlayer本身确实没有内置字幕相关API,但可以通过以下两种方式实现VTT字幕叠加:
方法一:CSS叠加自定义字幕层
这种方式通过手动解析VTT字幕,配合Dash回调同步播放器时间来显示对应字幕,灵活性高。
步骤:
- 解析VTT字幕文件,提取时间戳与对应文本
先写一个简单的Python函数处理VTT内容:
def parse_vtt(vtt_content): subtitles = [] lines = vtt_content.split('\n') i = 0 while i < len(lines): line = lines[i].strip() if '-->' in line: start, end = line.split('-->') start = start.strip() end = end.strip() # 转换为秒数方便对比 def time_to_sec(time_str): h, m, s = time_str.split(':') s, ms = s.split('.') return int(h)*3600 + int(m)*60 + int(s) + int(ms)/1000 start_sec = time_to_sec(start) end_sec = time_to_sec(end) # 获取字幕文本(可能多行) text = [] i +=1 while i < len(lines) and lines[i].strip() != '': text.append(lines[i].strip()) i +=1 subtitles.append({ 'start': start_sec, 'end': end_sec, 'text': ' '.join(text) }) i +=1 return subtitles
- 在布局中添加播放器和字幕容器
把字幕容器绝对定位在播放器上方,样式匹配播放器尺寸:
app = Dash(__name__) # 提前解析字幕(这里假设VTT内容已读取) with open('subtitles.vtt', 'r', encoding='utf-8') as f: vtt_content = f.read() subtitles = parse_vtt(vtt_content) app.layout = html.Div([ html.Div( [ dash_player.DashPlayer( id='vid1', controls=True, url="http://86.47.173.33:1935/playlist.m3u8", width='100%', style={'margin-top':'20px','margin-bottom':'20px'}, playing=True, muted=True ), html.Div( id='subtitle-overlay', style={ 'position': 'absolute', 'bottom': '50px', 'left': '50%', 'transform': 'translateX(-50%)', 'color': 'white', 'background': 'rgba(0,0,0,0.7)', 'padding': '8px 16px', 'border-radius': '4px', 'font-size': '18px', 'pointer-events': 'none', # 不干扰播放器操作 'text-align': 'center', 'max-width': '80%' } ) ], style={'position': 'relative', 'width': '100%'} ) ])
- 添加回调同步字幕显示
监听播放器的currentTime属性,匹配对应时间的字幕:
@app.callback( Output('subtitle-overlay', 'children'), Input('vid1', 'currentTime') ) def update_subtitle(current_time): if not current_time: return '' for sub in subtitles: if sub['start'] <= current_time <= sub['end']: return sub['text'] return ''
方法二:利用ReactPlayer原生track属性
DashPlayer是对ReactPlayer的封装,可以通过props参数直接传递ReactPlayer的原生属性,包括字幕轨道配置。
直接修改DashPlayer的调用,添加props参数指定VTT字幕:
dash_player.DashPlayer( id='vid1', controls=True, url="http://86.47.173.33:1935/playlist.m3u8", width='100%', style={'margin-top':'20px','margin-bottom':'20px'}, playing=True, muted=True, props={ 'tracks': [ { 'kind': 'subtitles', 'src': '/assets/subtitles.vtt', # 放在Dash的assets文件夹下 'srcLang': 'zh', 'label': '中文', 'default': True } ] } )
注意事项:
- 如果VTT文件是远程资源,需要确保服务器允许跨域访问
- 本地VTT文件建议放在Dash项目的
assets文件夹下,直接用相对路径引用 - 部分浏览器对VTT的格式有严格要求,确保字幕文件符合标准VTT规范
内容的提问来源于stack exchange,提问作者Jace999
相关产品推荐
相关产品推荐

