以下是使用C++語(yǔ)言調(diào)用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;
}
// 測(cè)試
int main() {
MediaInfo info = get_media_info("./example.mp4");
std::cout << "文件名:" << info.filename << std::endl;
std::cout << "時(shí)長(zhǎng):" << 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"
<< ", 聲道數(shù):" << info.audio_streams[i].second << std::endl;
}
return 0;
}
上述代碼通過(guò)AVFormatContext
結(jié)構(gòu)體和FFmpeg庫(kù)函數(shù)avformat_open_input
、avformat_find_stream_info
等,獲取MP4文件的視頻流和音頻流信息,并將結(jié)果存儲(chǔ)到MediaInfo
類中。在實(shí)際應(yīng)用中,可以將上述代碼封裝成一個(gè)函數(shù),方便地在程序中調(diào)用,達(dá)到自動(dòng)化處理多個(gè)視頻文件的目的。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-652304.html
編譯運(yùn)行:文章來(lái)源地址http://www.zghlxwxcb.cn/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
時(shí)長(zhǎng):5.888秒
比特率:434519bps
視頻流信息:
分辨率:720x480
音頻流信息:
采樣率:16000Hz, 聲道數(shù):1
到了這里,關(guān)于用ffmpeg解析mp4文件得到時(shí)長(zhǎng)、比特率、音視頻信息的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!