FFmpeg获取视频时长方法

一般在视频文件写完后,视频的时长会写在视频的头文件内。因此,只需要通过ffmpeg读取文件操作就可以获取视频时长信息。

此工程所用ffmpeg版本号为4.0.1  下载地址:https://ffmpeg.zeranoe.com/builds/

#include <stdio.h>
extern "C"{
#include <libavformat/avformat.h>
}


void main()
{
    AVFormatContext        *ifmt=NULL;

    avformat_network_init();
    ifmt=avformat_alloc_context();
    
    char* url="1.mp4";
    int ret=-1;
    ret=avformat_open_input(&ifmt,url,NULL,NULL);
    if(ret<0)
    {
        ret=-1;
        goto end;
    }

    显示输入流信息
    //printf("-----------rtsp流输入信息--------------\n");
    //av_dump_format(ifmt, 0, url,0);
    //printf("---------------------------------------\n");

    long tduration=ifmt->duration;         //这里获取的是微秒,需要转成秒

    printf("视频时长为%d秒\n",tduration/1000000);   


end:
    
    avformat_close_input(&ifmt);   //打开文件流后,需要关闭,否则会一直占用视频文件,无法进行视频文件的后续操作
    avformat_free_context(ifmt); 

    printf("ret=%d\n",ret);
    getchar();
}

工程下载地址:https://download.csdn.net/download/unfound/10558406

 

 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
FFmpeg中,获取视频时长可以通过AVFormatContext中的duration字段来实现,该字段表示音视频文件的总时长,单位是微秒(us)。如果duration为AV_NOPTS_VALUE,则表示无法获取时长。 具体实现代码如下: ```c AVFormatContext *fmt_ctx = NULL; if (avformat_open_input(&fmt_ctx, filename, NULL, NULL) != 0) { printf("Failed to open file '%s'\n", filename); return -1; } if (avformat_find_stream_info(fmt_ctx, NULL) < 0) { printf("Failed to retrieve input stream information\n"); return -1; } int64_t duration = fmt_ctx->duration; if (duration != AV_NOPTS_VALUE) { int hours, mins, secs, us; secs = duration / AV_TIME_BASE; us = duration % AV_TIME_BASE; mins = secs / 60; secs %= 60; hours = mins / 60; mins %= 60; printf("Duration: %02d:%02d:%02d.%02d\n", hours, mins, secs, (100 * us) / AV_TIME_BASE); } else { printf("Duration: N/A\n"); } avformat_close_input(&fmt_ctx); ``` 在这个例子中,我们首先使用avformat_open_input函数打开音视频文件,然后通过avformat_find_stream_info函数获取视频文件的流信息,接着获取AVFormatContext的duration字段,如果duration不为AV_NOPTS_VALUE,则表示获取到了时长,我们将其转换为时分秒的格式进行输出。最后,我们需要调用avformat_close_input函数关闭文件并释放资源。 需要注意的是,由于duration字段的单位是微秒,因此我们需要将其转换为秒,进而转换为时分秒格式。另外,如果获取时长失败,则duration的值将为AV_NOPTS_VALUE,我们需要做特殊处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值