备忘一个使用ffmepg获取视频的宽高时长等信息的代码,是使用ffmepg的api不是通过exe命令行的方式。至于用的ffmepg库和头文件等,我传github和CSDN各一份。地址在最后。
下面是代码,首先:
代码语言:javascript复制//引入ffmpeg的头文件和lib,自己处理好库的路径
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavutil/imgutils.h"
};
#pragma comment(lib,"avcodec.lib")
#pragma comment(lib,"avdevice.lib")
#pragma comment(lib,"avfilter.lib")
#pragma comment(lib,"avformat.lib")
#pragma comment(lib,"avutil.lib")
#pragma comment(lib,"postproc.lib")
#pragma comment(lib,"swresample.lib")
#pragma comment(lib,"swscale.lib")
然后使用:
代码语言:javascript复制int _tmain(int argc, _TCHAR* argv[])
{
//注册复用器,编码器等
av_register_all();
AVFormatContext *formatContext = NULL;
// 打开视频文件
if (avformat_open_input(&formatContext, "E:\TestCode\TestMfc\big_buck_bunny.mp4", NULL, NULL) != 0) {
printf("无法打开视频文件n");
return -1;
}
// 查找视频文件中的流信息
if (avformat_find_stream_info(formatContext, NULL) < 0) {
printf("无法查找视频流信息n");
return -1;
}
int videoStreamIndex = -1;
AVCodecParameters *codecParameters = NULL;
// 查找视频流
for (int i = 0; i < formatContext->nb_streams; i ) {
if (formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStreamIndex = i;
codecParameters = formatContext->streams[i]->codecpar;
break;
}
}
if (videoStreamIndex == -1) {
printf("无法查找视频流n");
return -1;
}
// 获取视频时长
int64_t duration = formatContext->streams[videoStreamIndex]->duration;
AVRational timeBase = formatContext->streams[videoStreamIndex]->time_base;
int durationInSeconds = duration * timeBase.num / timeBase.den;
int nWidth = codecParameters->width;
int nHeight = codecParameters->height;
printf("视频时长: %d 秒n", durationInSeconds);
// 关闭视频文件
avformat_close_input(&formatContext);
return 0;
}