以下是使用C++语言调用FFmpeg获取视频流和音频流信息的示例代码:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
extern "C" {
#include <libavformat/avformat.h>
}
class MediaInfo {
public:
std::string filename;
double duration;
int bitrate;
std::vector<std::pair<int, int>> video_streams; // (width, height)
std::vector<std::pair<int, int>> audio_streams; // (sample_rate, channels)
MediaInfo(const std::string& filename_) : filename(filename_) {}
};
MediaInfo get_media_info(const std::string& filename) {
int ret=0;
MediaInfo info(filename);
av_register_all();
AVFormatContext* format_ctx = nullptr;
ret=avformat_open_input(&format_ctx, filename.c_str(), nullptr, nullptr);
if(ret < 0)
{
std::cout << "avformat_open_input error\n";
return info;
}
avformat_find_stream_info(format_ctx, nullptr);
info.duration = static_cast<double>(format_ctx->duration) / AV_TIME_BASE;
info.bitrate = format_ctx->bit_rate;
for (unsigned int i = 0; i < format_ctx->nb_streams; i++) {
if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
int width = format_ctx->streams[i]->codecpar->width;
int height = format_ctx->streams[i]->codecpar->height;
info.video_streams.push_back({width, height});
}
else if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
int sample_rate = format_ctx->streams[i]->codecpar->sample_rate;
int channels = format_ctx->streams[i]->codecpar->channels;
info.audio_streams.push_back({sample_rate, channels});
}
}
avformat_close_input(&format_ctx);
return info;
}
// 测试
int main() {
MediaInfo info = get_media_info("./example.mp4");
std::cout << "文件名:" << info.filename << std::endl;
std::cout << "时长:" << info.duration << "秒" << std::endl;
std::cout << "比特率:" << info.bitrate << "bps" << std::endl;
std::cout << "视频流信息:" << std::endl;
for (unsigned int i = 0; i < info.video_streams.size(); i++) {
std::cout << " 分辨率:" << info.video_streams[i].first << "x" << info.video_streams[i].second << std::endl;
}
std::cout << "音频流信息:" << std::endl;
for (unsigned int i = 0; i < info.audio_streams.size(); i++) {
std::cout << " 采样率:" << info.audio_streams[i].first << "Hz"
<< ", 声道数:" << info.audio_streams[i].second << std::endl;
}
return 0;
}
上述代码通过AVFormatContext
结构体和FFmpeg库函数avformat_open_input
、avformat_find_stream_info
等,获取MP4文件的视频流和音频流信息,并将结果存储到MediaInfo
类中。在实际应用中,可以将上述代码封装成一个函数,方便地在程序中调用,达到自动化处理多个视频文件的目的。文章来源:https://www.toymoban.com/news/detail-652304.html
编译运行:文章来源地址https://www.toymoban.com/news/detail-652304.html
book@ubuntu:~/Desktop/c++_study$ g++ -g -o test_ff test_ff.cpp -lavformat
book@ubuntu:~/Desktop/c++_study$ ./test_ff
文件名:./example.mp4
时长:5.888秒
比特率:434519bps
视频流信息:
分辨率:720x480
音频流信息:
采样率:16000Hz, 声道数:1
到了这里,关于用ffmpeg解析mp4文件得到时长、比特率、音视频信息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!