以下は、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
などを通じてMP4ファイルの解像度を取得しavformat_find_stream_info
、std::vector<int>
結果を形式で返します。実際のアプリケーションでは、上記のコードを関数にカプセル化して、プログラム内で簡単に呼び出すことができ、複数のビデオ ファイルを自動的に処理するという目的を達成できます。