以下是使用C++语言调用FFmpeg获取MP4文件分辨率的示例代码:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
extern "C" {
#include <libavformat/avformat.h>
}
std::vector<int> get_resolution(const std::string& video_path) {
AVFormatContext* format_ctx = nullptr;
avformat_open_input(&format_ctx, video_path.c_str(), nullptr, nullptr);
avformat_find_stream_info(format_ctx, nullptr);
int video_index = -1;
for (unsigned int i = 0; i < format_ctx->nb_streams; i++) {
if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
video_index = i;
break;
}
}
int width = format_ctx->streams[video_index]->codecpar->width;
int height = format_ctx->streams[video_index]->codecpar->height;
avformat_close_input(&format_ctx);
return {width, height};
}
// 测试
int main() {
std::vector<int> resolution = get_resolution("example.mp4");
std::cout << "视频分辨率:" << resolution[0] << "x" << resolution[1] << std::endl;
return 0;
}
上述代码通过AVFormatContext
结构体和FFmpeg库函数avformat_open_input
、avformat_find_stream_info
等,获取MP4文件分辨率,并将结果以std::vector<int>
形式返回。在实际应用中,可以将上述代码封装成一个函数,方便地在程序中调用,达到自动化处理多个视频文件的目的。