将音频帧AVFrame的格式有AAC转为PCM后,再将AVFrame中的data转为QByteArray 之后,用QIODevice写入,QAudioOutput播放音频,但是播放无音频。
源码:
//初始化AVFrame
pFrame = av_frame_alloc();
pFramePCM = av_frame_alloc();
const AVChannelLayout *out_ch_layout = &out_codec_ctx->ch_layout;
const AVChannelLayout *in_ch_layout = &pCodecCtx->ch_layout;
SwrContext *swr_ctx2 = swr_alloc();
//创建和配置SwrContext上下文,指定转换后的音频格式,包括输入输出采样率、通道布局、样本格式
swr_alloc_set_opts2(&swr_ctx2,out_ch_layout, AV_SAMPLE_FMT_S16, out_codec_ctx->sample_rate,in_ch_layout, pCodecCtx->sample_fmt, pCodecCtx->sample_rate,0, NULL);
swr_init(swr_ctx2);
packet = av_packet_alloc();
while (av_read_frame(pFormatCtx, packet) >= 0) {
if (packet->stream_index == audioStream) {
if(avcodec_send_packet(pCodecCtx, packet) == 0){
while (avcodec_receive_frame(pCodecCtx, pFrame) >= 0) {
int outNbSamples = swr_get_out_samples(swr_ctx2, pFrame->nb_samples);
av_samples_alloc((uint8_t **)&pFramePCM->data, &pFramePCM->linesize[0],pCodecCtx->ch_layout.nb_channels, outNbSamples,AV_SAMPLE_FMT_S16, 1);
swr_convert(swr_ctx2, pFramePCM->data, outNbSamples,(const uint8_t **)pFrame->data, pFrame->nb_samples);
QByteArray audioData((char *)pFramePCM->data, pFramePCM->nb_samples * pCodecCtx->ch_layout.nb_channels * 3);
streamOut->write(audioData.data(),audioData.size());
qDebug()<<"接收到了音频";
}
}
}
av_packet_unref(packet);
}