ffmpeg 2.0 音频解码出来的数据格式不符合Android音频格式
问题原因:
ffmpeg2.0最新的解码出来的数据是 sample_fmts = AV_SAMPLE_FMT_FLTP
android需要的音频格式:sample_fmts (AV_SAMPLE_FMT_S8, AV_SAMPLE_FMT_S16)
解决方法:
1, 创建转换对象
void audio_swr_resampling_audio_init(SwrContext **swr_ctx,TargetAudioParams *targetAudioParams,AVCodecContext *codec){
if(codec->sample_fmt == AV_SAMPLE_FMT_S16 || codec->sample_fmt == AV_SAMPLE_FMT_S32 ||codec->sample_fmt == AV_SAMPLE_FMT_U8){
LOGE("codec->sample_fmt:%d",codec->sample_fmt);
if(*swr_ctx){
swr_free(swr_ctx);
*swr_ctx = NULL;
}
return;
}
if(*swr_ctx){
swr_free(swr_ctx);
}
*swr_ctx = swr_alloc();
if(!*swr_ctx){
LOGE("swr_alloc failed");
return;
}
/* set options */
av_opt_set_int(*swr_ctx, "in_channel_layout", codec->channel_layout, 0);
av_opt_set_int(*swr_ctx, "in_sample_rate", codec->sample_rate, 0);
av_opt_set_sample_fmt(*swr_ctx, "in_sample_fmt", codec->sample_fmt, 0);
av_opt_set_int(*swr_ctx, "out_channel_layout", targetAudioParams->channel_layout, 0);
av_opt_set_int(*swr_ctx, "out_sample_rate", targetAudioParams->sample_rate, 0);
av_opt_set_sample_fmt(*swr_ctx, "out_sample_fmt", targetAudioParams->sample_fmt, 0);// AV_SAMPLE_FMT_S16
/* initialize the resampling context */
int ret = 0;
if ((ret = swr_init(*swr_ctx)) < 0) {
LOGE("Failed to initialize the resampling context\n");
if(*swr_ctx){
swr_free(swr_ctx);
*swr_ctx = NULL;
}
return;
}
}
2, 转换(AV_SAMPLE_FMT_FLTP àAV_SAMPLE_FMT_S16)
int audio_swr_resampling_audio(SwrContext *swr_ctx,TargetAudioParams *targetAudioParams,AVFrame *audioFrame,uint8_t **targetData){
int len = swr_convert(swr_ctx,targetData,audioFrame->nb_samples,audioFrame->extended_data,audioFrame->nb_samples);
if(len < 0){
LOGE("error swr_convert");
goto end;
}
int dst_bufsize = len * targetAudioParams->channels * av_get_bytes_per_sample(targetAudioParams->sample_fmt);
LOGI(" dst_bufsize:%d",dst_bufsize);
return dst_bufsize;
end:
return -1;
}
3, 销毁
最后处理完成销毁对象
void audio_swr_resampling_audio_destory(SwrContext **swr_ctx){
if(*swr_ctx){
swr_free(swr_ctx);
*swr_ctx = NULL;
}
}