您当前的位置: 首页 > 

龚建波

暂无认证

  • 4浏览

    0关注

    313博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

使用 FFmpeg 获取音频文件编码格式、采样率等信息

龚建波 发布时间:2020-11-20 01:31:31 ,浏览量:4

参考博客:用FFmpeg获取视频流+音频流的信息(编码格式、分辨率、帧率、播放时长...)_zhoubotong2012的博客-CSDN博客_ffmpeg获取视频编码格式

参考博客:用AVCodecParameters代替AVCodecContext_luotuo44的博客-CSDN博客_avcodec_parameters_to_context

我是在 Qt 里跑的,所以路径用了 QString 传递,然后 FFmpeg 使用的 4.2 版本进行测试。对于相关函数的含义,一般 FFmpeg 源文件有注释。

(2020-12-30 修改)之前用的 AVFormatContext 来获取的比特率,如果是视频文件这就不能作为音频的比特率了,所以改为了 AVCodecContext 来获取。不过有些文件的 AVCodecContext 可能获取不到比特率信息,这时候再使用 AVFormatContext 提供的信息。

(2022-08-25 修改)之前用av_get_bytes_per_sample(guard.codecCtx->sample_fmt)获取采样精度,因为参数枚举AVSampleFormat并不对应文件实际的采样精度,所以读取出来的信息如24bit时会识别成32bit,现在用av_get_bits_per_sample(guard.codecParam->codec_id)来获取。

extern "C" {
#include 
#include 
#include 
}

#include 
#include 

//通过一个guard对象来确保资源释放
struct AudioInfoGuard {
    //格式化I/O上下文
    AVFormatContext *formatCtx = NULL;
    //解码器
    AVCodec *codec = NULL;
    //解码器上下文
    AVCodecContext *codecCtx = NULL;
    //参数信息
    AVCodecParameters *codecParam = NULL;

    ~AudioInfoGuard() {
        if(codecCtx){
            avcodec_free_context(&codecCtx);
        }
        if(formatCtx){
            avformat_close_input(&formatCtx);
            avformat_free_context(formatCtx);
        }
    }
};

//是在Qt中使用的,所以传递的QString
bool getAudioInfo(const QString &filepath)
{
    //用的utf8编码,这里转换下
    QByteArray temp=filepath.toUtf8();
    const char *path=temp.constData();
    //const char *filepath="D:/Download/12.wav";

    //借助析构函数来释放
    AudioInfoGuard guard;

    //打开输入流并读取头
    //流要使用avformat_close_input关闭
    //成功时返回=0
    int result=avformat_open_input(&guard.formatCtx, path, NULL, NULL);
    if (result!=0||guard.formatCtx==NULL){
        return false;
    }

    //读取文件获取流信息,把它存入AVFormatContext中
    //正常时返回>=0
    if (avformat_find_stream_info(guard.formatCtx, NULL) < 0) {
        return false;
    }

    //获取元信息,曲名,歌手等
    //AVDictionaryEntry *tag = NULL;
    //while (tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))
    //{
    //    qDebug()            
关注
打赏
1655829268
查看更多评论
0.0366s