You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过命令或C代码获取H265格式视频文件的时长?

获取H.265裸流文件时长的方法(命令行+代码实现)

命令行工具方案(用ffprobe)

ffprobe完全支持解析H.265裸流,不需要额外工具,直接用以下命令即可:

  • 输出秒级时长(浮点数):

    ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 input.h265
    

    参数说明:

    • -v error:只输出错误信息,屏蔽冗余日志
    • -show_entries format=duration:指定获取文件的时长字段
    • -of default=noprint_wrappers=1:nokey=1:简化输出格式,仅返回时长数值
  • 输出时:分:秒格式的时长:

    ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 input.h265 | awk '{printf "%02d:%02d:%02d\n",int($1/3600),int(($1%3600)/60),int($1%60)}'
    

C代码实现(基于FFmpeg API)

如果需要在程序中获取时长,可以用FFmpeg的原生API实现,核心是解析H.265流的时间戳总和:

#include <libavformat/avformat.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <input.h265>\n", argv[0]);
        return 1;
    }

    av_register_all();
    AVFormatContext *fmt_ctx = NULL;

    // 打开H.265裸流,指定输入格式为h265(也可省略让API自动探测)
    if (avformat_open_input(&fmt_ctx, argv[1], av_find_input_format("h265"), NULL) != 0) {
        fprintf(stderr, "Failed to open input file\n");
        return 1;
    }

    // 读取流的详细信息
    if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
        fprintf(stderr, "Failed to retrieve stream info\n");
        avformat_close_input(&fmt_ctx);
        return 1;
    }

    // 计算时长:AVFormatContext.duration单位是微秒,转换为秒
    double duration = (double)fmt_ctx->duration / AV_TIME_BASE;
    printf("Duration: %.2f seconds\n", duration);

    avformat_close_input(&fmt_ctx);
    return 0;
}

编译命令(需提前安装FFmpeg开发库):

gcc -o h265_duration h265_duration.c -lavformat -lavcodec -lavutil

注意事项

H.265裸流没有容器元数据,时长是通过遍历所有帧的时间戳计算得出的,因此需要确保文件完整,否则计算结果会不准确。

内容的提问来源于stack exchange,提问作者Pratik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:00:49