編集 2013 年 4 月 9 日: libswresample を使用してこれを行う方法を考え出しました... はるかに高速です!
過去 2 ~ 3 年のある時点で、FFmpeg の AAC デコーダーの出力形式が AV_SAMPLE_FMT_S16 から AV_SAMPLE_FMT_FLTP に変更されました。つまり、各オーディオ チャネルには独自のバッファがあり、各サンプル値は -1.0 から +1.0 にスケーリングされた 32 ビット浮動小数点値です。
AV_SAMPLE_FMT_S16 の場合、データは単一のバッファーにあり、サンプルはインターリーブされ、各サンプルは -32767 から +32767 までの符号付き整数です。
AV_SAMPLE_FMT_S16 としてのオーディオが本当に必要な場合は、自分で変換する必要があります。私はそれを行う2つの方法を考え出しました:
1. libswresample を使用する(推奨)
#include "libswresample/swresample.h"
...
SwrContext *swr;
...
// Set up SWR context once you've got codec information
swr = swr_alloc();
av_opt_set_int(swr, "in_channel_layout", audioCodec->channel_layout, 0);
av_opt_set_int(swr, "out_channel_layout", audioCodec->channel_layout, 0);
av_opt_set_int(swr, "in_sample_rate", audioCodec->sample_rate, 0);
av_opt_set_int(swr, "out_sample_rate", audioCodec->sample_rate, 0);
av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
swr_init(swr);
...
// In your decoder loop, after decoding an audio frame:
AVFrame *audioFrame = ...;
int16_t* outputBuffer = ...;
swr_convert(&outputBuffer, audioFrame->nb_samples, audioFrame->extended_data, audioFrame->nb_samples);
そして、それはあなたがしなければならないすべてです!
2.Cで手作業で行う(元の回答、お勧めしません)
したがって、デコード ループでは、オーディオ パケットを取得したら、次のようにデコードします。
AVCodecContext *audioCodec; // init'd elsewhere
AVFrame *audioFrame; // init'd elsewhere
AVPacket packet; // init'd elsewhere
int16_t* outputBuffer; // init'd elsewhere
int out_size = 0;
...
int len = avcodec_decode_audio4(audioCodec, audioFrame, &out_size, &packet);
そして、オーディオのフル フレームがある場合は、かなり簡単に変換できます。
// Convert from AV_SAMPLE_FMT_FLTP to AV_SAMPLE_FMT_S16
int in_samples = audioFrame->nb_samples;
int in_linesize = audioFrame->linesize[0];
int i=0;
float* inputChannel0 = (float*)audioFrame->extended_data[0];
// Mono
if (audioFrame->channels==1) {
for (i=0 ; i<in_samples ; i++) {
float sample = *inputChannel0++;
if (sample<-1.0f) sample=-1.0f; else if (sample>1.0f) sample=1.0f;
outputBuffer[i] = (int16_t) (sample * 32767.0f);
}
}
// Stereo
else {
float* inputChannel1 = (float*)audioFrame->extended_data[1];
for (i=0 ; i<in_samples ; i++) {
outputBuffer[i*2] = (int16_t) ((*inputChannel0++) * 32767.0f);
outputBuffer[i*2+1] = (int16_t) ((*inputChannel1++) * 32767.0f);
}
}
// outputBuffer now contains 16-bit PCM!
わかりやすくするために、いくつかのことを省略しています...モノパスのクランプは、理想的にはステレオパスで複製する必要があります。また、コードは簡単に最適化できます。