如何使用libavcodec/ffmpeg查找视频文件的持续时间

Kun*_*yas 17 c++ ffmpeg

我需要一个库来执行视频文件的长度,大小等基本功能(我猜测元数据或标签)所以我选择了ffmpeg.有效的视频格式主要是电影文件中流行的格式.wmv,wmvhd,avi,mpeg,mpeg-4等.如果可以,请帮助我了解用于了解视频文件持续时间的方法.我在Linux平台上.

mgi*_*uca 34

libavcodec非常难以编程,而且很难找到文档,所以我感到很痛苦.本教程是一个好的开始.是主要的API文档.

查询视频文件的主要数据结构是AVFormatContext.在本教程中,这是您打开的第一件事,使用av_open_input_file- 该文档说它已被弃用,您应该使用avformat_open_input.

从那里,您可以从AVFormatContext中读取属性:duration在几分之一秒内(参见文档),file_size以字节为单位bit_rate等.

所以把它放在一起应该看起来像:

AVFormatContext* pFormatCtx = avformat_alloc_context();
avformat_open_input(&pFormatCtx, filename, NULL, NULL);
int64_t duration = pFormatCtx->duration;
// etc
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
Run Code Online (Sandbox Code Playgroud)

如果您的文件格式没有标题,例如MPEG,您可能需要在avformat_open_input读取数据包中的信息后添加此行(可能更慢):

avformat_find_stream_info(pFormatCtx, NULL);
Run Code Online (Sandbox Code Playgroud)

编辑:

  • 在代码示例中添加了pFormatCtx的分配和解除分配.
  • 添加avformat_find_stream_info(pFormatCtx, NULL)到处理没有标题的视频类型,如MPEG

  • 在我看来pFormatCtx应该初始化为NULL?否则,avformat_open_input假定调用方已经分配了上下文。 (2认同)

小智 13

我不得不加一个电话

avformat_find_stream_info(pFormatCtx,NULL)
Run Code Online (Sandbox Code Playgroud)

之后avformat_open_input得到mgiuca的工作答案.(不能发表评论)

#include <libavformat/avformat.h>
...
av_register_all();
AVFormatContext* pFormatCtx = avformat_alloc_context();
avformat_open_input(&pFormatCtx, filename, NULL, NULL);
avformat_find_stream_info(pFormatCtx,NULL)
int64_t duration = pFormatCtx->duration;
// etc
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
Run Code Online (Sandbox Code Playgroud)

持续时间以uSeconds为单位,除以AV_TIME_BASE得秒.