ffmpeg 获取视频的时长

简单写个程序获取视频的时长,以便做视频播放器的进度条。
很简单,头文件我懒的敲了,直接复制别的,所以有些多余。
代码如下:

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
#include <libavutil/avstring.h>
#include <libavutil/opt.h>
#include <libavutil/time.h>
#include <libavdevice/avdevice.h>

int main(int argc,char *argv[])
{
    AVFormatContext *pFormatCtx = NULL;
    int times;

    av_register_all();
    avformat_network_init();

    if(avformat_open_input(&pFormatCtx,argv[1],NULL,NULL) !=0 )
    //if(avformat_open_input(&pFormatCtx, "http://vfx.mtime.cn/Video/2019/01/15/mp4/190115161611510728_480.mp4", NULL, NULL)!=0)
    //if(avformat_open_input(&pFormatCtx, "/home/llw/Desktop/output.mp4", NULL, NULL)!=0)
    {   
        fprintf(stderr,"err!");
        exit(1);
    }   

    times = pFormatCtx->duration/1000000;	//duration单位是us,转化为秒
    printf("time:%d\n",times);

    avformat_close_input(&pFormatCtx);	//释放动作

    return 0;
}

看图:
在这里插入图片描述
可以看到获取到了视频的时长,分别是145秒和254秒。
用别的播放器打开看看验证是否正确:
在这里插入图片描述
可以看到时间为4分14,对应上面的254秒。
程序OK!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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,我们需要做特殊处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值