在 Python 中向 Plotly Dash 视频播放器添加字幕

问题描述 投票:0回答:1

我正在尝试使用 Python 将字幕添加到我的 Plotly Dash 视频播放器,即 VTT 字幕叠加层。我找不到任何关于此的示例或说明。

from dash import Dash, dcc, html, Input, Output, State
import dash_player

在某个 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
                )

文档中 DashPlayer 对象没有处理字幕轨道的方法。也许这可以在 CSS 中处理?

查找一些 React 播放器示例。

python plotly-dash video-player
1个回答
0
投票

我最终的策略是创建一个 div(“字幕容器”)作为布局中 DashPlayer 的兄弟:

dash_player.DashPlayer(
    id='vid',
    controls = True,
    url = None,
    style={'margin-top':'20px','margin-bottom':'20px', 'margin-left':'10px'},
    playing= False,
    muted= False
),
html.Div(
    id='subtitle-container',
    children=[html.P("subtitle text")],
    style={}
),

我使用 DashPlayer 的“当前时间”回调在字幕容器中实现了自己的逻辑来显示字幕。

 @app.callback([Output('subtitle-container','children'),Output('subtitle-container', 'style')],
              [Input('vid', 'currentTime')])
def update_subtitles(current_time):

    subtitle_text = get_subtitle_for_time(current_time)

    # Determine whether subtitles are being displayed
    subtitles_displayed = bool(subtitle_text)

    # Set the alpha value based on whether subtitles are being displayed
    alpha_value = 0 if not subtitles_displayed else 0.5

    # Update subtitle container style
    subtitle_style={
                'position':'absolute',
                'bottom':'6%',
                'left': '25%',
                'width':'50%',
                'background-color':f'rgba(30,30,30, {alpha_value})',
                'padding':'5px',
                'whiteSpace':'pre-wrap',
                'color':'white',
                'text-align':'center'
                }

    return subtitle_text, subtitle_style

该回调根据玩家当前时间返回相关字幕,并显示在“字幕容器”中。我还实现了逻辑来确定字幕的样式,当存在标题时为半透明深色背景,当不存在标题时则没有背景(alpha = 0)。

为了最初收集所有字幕,我解析了一个 SRT 文件,以生成字幕项列表。每个字幕项都是包含 3 个项目的列表:开始时间、结束时间和字幕文本。例如

[1185.65, 1193.74, "You're the one who was frowning.\nFrisco. San Francisco. Exactly.']. 

时间已从原始 SRT 时间戳转换而来。

获取适合玩家当前时间的提示只需:

def get_subtitle_for_time(current_time):
    for caption in captions:
        if current_time <= caption[1]:
            if current_time >= caption[0]:
                return caption[2]
            return ''

© www.soinside.com 2019 - 2024. All rights reserved.