大家好,我用qt播放ffmpeg解码重采样的音频有杂音,有大神帮看下么

void MediaPlayer::onDecodeAudio(AVFrame *frame, double pts){
qDebug()<<"a pts="<<pts;
// char* data=(char *)frame->data;
// pMeidaPlayer->pIODevice->write(data);
// uint64_t out_channel_layout=AV_CH_LAYOUT_STEREO; //定义目标音频参数
//nb_samples: AAC-1024 MP3-1152
AVCodecContext *pAudioCodecCtx=pMeidaPlayer->pFormatContext->streams[pMeidaPlayer->mAudioStreamIndex]->codec;
int out_nb_samples=pAudioCodecCtx->frame_size;
AVSampleFormat out_sample_fmt=AV_SAMPLE_FMT_S16;
int out_sample_rate=44100;
// int out_channels=av_get_channel_layout_nb_channels(out_channel_layout);
int out_channels=pAudioCodecCtx->channels;
qDebug()<<"ch="<<out_channels;
//Out Buffer Size
int out_buffer_size=av_samples_get_buffer_size(NULL,out_channels ,out_nb_samples,out_sample_fmt, 0);//计算转换后数据大小
if(pMeidaPlayer->audio_out_buffer==NULL)
pMeidaPlayer->audio_out_buffer=(uint8_t *)av_malloc(192000*2);//申请输出缓冲区
//FIX:Some Codec's Context Information is missing
uint64_t in_channel_layout=av_get_default_channel_layout(pAudioCodecCtx->channels);
//Swr

if(pMeidaPlayer->pSwrContext==NULL)
{
pMeidaPlayer->pSwrContext= swr_alloc();
pMeidaPlayer->pSwrContext=swr_alloc_set_opts(pMeidaPlayer->pSwrContext,pAudioCodecCtx->channel_layout, out_sample_fmt, out_sample_rate,
pAudioCodecCtx->channel_layout ,pAudioCodecCtx->sample_fmt , pAudioCodecCtx->sample_rate,0, NULL);//配置源音频参数和目标音频参数
swr_init(pMeidaPlayer->pSwrContext);
}
SwrContext *audio_convert_ctx=pMeidaPlayer->pSwrContext;

int len2=swr_convert(audio_convert_ctx,&pMeidaPlayer->audio_out_buffer, out_buffer_size,(const uint8_t **)frame->data , frame->nb_samples);
int resampled_data_size = len2 * out_channels * av_get_bytes_per_sample(out_sample_fmt);//每声道采样数 x 声道数 x 每个采样字节数

// fwrite(audio_out_buffer,1,resampled_data_size,pcm);//pcm记录
// fflush(pcm);
if(len2>0)
pMeidaPlayer->pIODevice->write((char *)pMeidaPlayer->audio_out_buffer,out_buffer_size);

usleep(1000000/pMeidaPlayer->mFrameRate);
}

swr_alloc_set_opts 函数的输入的sample_fmt可能错了,尝试不使用AVCodecContext 里面的Sample_fmt,写成AV_SAMPLE_FMT_FLTP试试。
温馨提示:答案为网友推荐,仅供参考