在实际的项目中,从音频设备采集到的音频的类型和编码器类型(aac ,amr)通常是不一致的。
那么我们首先需要做重采样的过程。利用swr_convert 重新采样。
这时候我们可能会遇到另外一个问题。就是在encode_audio的时候遇到
more samples than frame size (avcodec_encode_audio2) 的问题。
问题的原因在于 我们编码器的frame_size 比采集到的fram->nb_samples小
/* check for valid frame size */
if (frame) {
if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
if (frame->nb_samples > avctx->frame_size) {
av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
return AVERROR(EINVAL);
}
} else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
if (frame->nb_samples < avctx->frame_size &&
!avctx->internal->last_audio_frame) {
ret = pad_last_frame(avctx, &padded_frame, frame);
if (ret < 0)
return ret;
frame = padded_frame;
avctx->internal->last_audio_frame = 1;
}
if (frame->nb_samples != avctx->frame_size) {
av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
ret = AVERROR(EINVAL);
goto end;
}
}
}
解决的方案是:每次采集到的frame数据保存到一个AUDIO FIFO中,每次等凑齐 刚好frame_size大小的数据(请注意这里是刚好,网上有人说拆分AVframe,本人在ffmpeg2.1用这个办法没办法解决),接着把这些数据一口气encode。
如果有剩余的数据就存储到下一次encode。可以使用audio_fifo_来操作数据
http://www.ffmpeg.org/doxygen/1.0/audio__fifo_8c-source.html