文档目录

一、什么时候需要重采样

你的游戏/桌面采集的音频是 48000Hz,但推流到某个平台要求 44100Hz。
或者来源是 2 声道,平台要求 1 声道(混音)。

这时就需要音频重采样(resample)。

FFmpeg 提供 libswresample:
swr_init(src_rate, src_channels, src_fmt,
         dst_rate, dst_channels, dst_fmt)
→ 一次调用完成采样率转换 + 声道布局转换 + 格式转换
extern "C" {
#include <libswresample/swresample.h>
}

struct AudioResampler {
    SwrContext* swr = nullptr;

    bool init(int src_rate, int dst_rate, int channels) {
        swr = swr_alloc_set_opts(nullptr,
            dst_rate, AV_CH_LAYOUT_STEREO, AV_SAMPLE_FLT_FLTP,   // 输出
            src_rate, AV_CH_LAYOUT_STEREO, AV_SAMPLE_FLT_FLTP,   // 输入
            0, nullptr);
        return swr_init(swr) >= 0;
    }

    // 输入 AVFrame(src_format),输出转换后的 AVFrame
    AVFrame* resample(AVFrame* src) {
        AVFrame* dst = av_frame_alloc();
        dst->format = AV_SAMPLE_FLT_FLTP;
        dst->channel_layout = AV_CH_LAYOUT_STEREO;
        dst->sample_rate = dst_rate;
        dst->nb_samples = src->nb_samples;
        av_frame_get_buffer(dst, 0);

        swr_convert(swr,
                    dst->data, dst->nb_samples,
                    (const uint8_t**)src->data, src->nb_samples);

        return dst;
    }
};