写一个ununtu C++ 程序,调用ffmpeg , 来判断一个数字电影的音频文件mxf 的 采样率(频率),通道数, 采样位数
以下是一个 Ubuntu C++ 程序,使用 FFmpeg API 来检测数字电影音频 MXF 文件的 采样率(频率)、通道数、采样位数:
1. 安装 FFmpeg 开发库
bash
sudo apt update sudo apt install libavformat-dev libavcodec-dev libavutil-dev
2. C++ 程序代码 (check_mxf_audio.cpp
)
cpp
#include <iostream> #include <string>extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> }void get_audio_info(const std::string& filename) {// 初始化 FFmpegavformat_network_init();// 打开文件AVFormatContext* format_ctx = nullptr;if (avformat_open_input(&format_ctx, filename.c_str(), nullptr, nullptr) != 0) {std::cerr << "Error: Could not open file " << filename << std::endl;return;}// 获取流信息if (avformat_find_stream_info(format_ctx, nullptr) < 0) {std::cerr << "Error: Could not find stream info" << std::endl;avformat_close_input(&format_ctx);return;}// 查找音频流bool audio_found = false;for (unsigned int i = 0; i < format_ctx->nb_streams; i++) {AVStream* stream = format_ctx->streams[i];if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {audio_found = true;// 获取音频参数int sample_rate = stream->codecpar->sample_rate;int channels = stream->codecpar->channels;int bits_per_sample = stream->codecpar->bits_per_raw_sample;// 如果 bits_per_raw_sample 为0,尝试从 sample_fmt 推断if (bits_per_sample == 0) {AVCodec* codec = avcodec_find_decoder(stream->codecpar->codec_id);if (codec) {AVCodecContext* codec_ctx = avcodec_alloc_context3(codec);avcodec_parameters_to_context(codec_ctx, stream->codecpar);bits_per_sample = av_get_bytes_per_sample(codec_ctx->sample_fmt) * 8;avcodec_free_context(&codec_ctx);}}// 打印结果std::cout << "Audio Stream #" << i << ":\n"<< " Sample Rate: " << sample_rate << " Hz\n"<< " Channels: " << channels << "\n"<< " Bits per Sample: " << bits_per_sample << "-bit\n";}}if (!audio_found) {std::cerr << "Error: No audio stream found in file" << std::endl;}// 释放资源avformat_close_input(&format_ctx); }int main(int argc, char* argv[]) {if (argc < 2) {std::cerr << "Usage: " << argv[0] << " <input.mxf>\n";return 1;}std::string filename = argv[1];get_audio_info(filename);return 0; }
3. 编译程序
bash
g++ check_mxf_audio.cpp -o check_mxf_audio -lavformat -lavcodec -lavutil
4. 运行测试
bash
./check_mxf_audio input.mxf
输出示例:
text
Audio Stream #1:Sample Rate: 48000 HzChannels: 6Bits per Sample: 24-bit
5. 关键代码解析
代码部分 | 作用 |
---|---|
avformat_open_input() | 打开 MXF 文件 |
avformat_find_stream_info() | 探测流信息 |
stream->codecpar->sample_rate | 获取采样率 |
stream->codecpar->channels | 获取通道数 |
stream->codecpar->bits_per_raw_sample | 获取采样位数 |
av_get_bytes_per_sample() | 从采样格式推断位数 |
6. 特殊情况处理
-
如果
bits_per_raw_sample
为 0:
程序会尝试从sample_fmt
推断位数(例如AV_SAMPLE_FMT_S16
= 16-bit)。 -
多音频流:
程序会列出所有音频流的信息。
7. 替代方案(直接使用 ffprobe)
如果不需要 C++ 集成,可直接用命令行:
bash
ffprobe -v error -select_streams a -show_entries stream=sample_rate,channels,bits_per_raw_sample -of default=noprint_wrappers=1:nokey=1 input.mxf
这个方案适合需要 程序化处理 MXF 音频 的场景(如自动化质检工具)。如果需要进一步扩展(如写入 XML/JSON),可以添加相关库支持。