【问题标题】:Python code to convert ffmpeg time duration value to seconds将ffmpeg持续时间值转换为秒的Python代码
【发布时间】:2021-02-28 19:06:46
【问题描述】:

我正在寻找 python 3.x 代码,它可以在 ffmpeg 的 time duration format 中获取用户提供的值,并为该持续时间表示的秒数提供一个浮点数。它将解析文档中描述的两种格式并处理第二种格式的 s/ms/us 前缀。我唯一不需要的是可选的否定。我最需要这个,所以我可以为淡入淡出和淡入淡出过滤器提供正确的“开始时间”(秒)。

请注意,我不是在问如何获取输入文件的持续时间。这些是用户提供的字符串值。

【问题讨论】:

  • 淡入淡出过滤器start_time(和duration)可以接受以秒为单位或格式为01:23:45.00的值。到目前为止,我认为不需要执行任何转换。唯一的问题是您将不得不转义 :
  • 对不起?来自fade documentation,“指定开始应用淡入淡出效果的帧的时间戳(以秒为单位)。”
  • 我在评论之前尝试过。文档应该说,“指定开始应用淡入淡出效果的帧的时间戳。有关接受的语法,请参阅(ffmpeg-utils)the Time duration section in the ffmpeg-utils(1) manual。”
  • 无论如何,它并不能完全解决我的问题。例如,用户可以指定结束时间戳和淡出持续时间(以秒为单位)。我需要使用结束时间戳并减去淡入淡出持续时间才能开始淡出。最简单的方法是以秒为单位获取结束时间戳并减去。此外,我还有其他用途——它主要用于淡入淡出。

标签: python-3.x ffmpeg


【解决方案1】:

我想出了以下代码。它并不完美,因为它可能会接受一些 ffmpeg 不会接受的字符串,但它应该足够接近我的即时需求。

def duration_to_seconds(duration):
    """
    Converts an ffmpeg duration string into a decimal representing the number of seconds
    represented by the duration string; None if the string is not parsable.
    """
    pattern = r'^((((?P<hms_grp1>\d*):)?((?P<hms_grp2>\d*):)?((?P<hms_secs>\d+([.]\d*)?)))|' \
              '((?P<smu_value>\d+([.]\d*)?)(?P<smu_units>s|ms|us)))$'
    match = re.match(pattern, duration)
    if match:
        groups = match.groupdict()
        if groups['hms_secs'] is not None:
            value = float(groups['hms_secs'])
            if groups['hms_grp2'] is not None:
                value += int(groups['hms_grp1']) * 60 * 60 + int(groups['hms_grp2']) * 60
            elif groups['hms_grp1'] is not None:
                value += int(groups['hms_grp1']) * 60
        else:
            value = float(groups['smu_value'])
            units = groups['smu_units']
            if units == 'ms':
                value /= 1000.0
            elif units == 'us':
                value /= 1000000.0
        return value
    else:
        return None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 2020-05-03
    相关资源
    最近更新 更多