从0开始做播放器---音频播放有杂音且音调异常

时间:2022-07-22
本文章向大家介绍从0开始做播放器---音频播放有杂音且音调异常,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我的播放器,音频像是电视信号不好,需要动一下天线,有那种沙沙声。 明确音频数据问题,在get音频数据处找问题。

  1. 音调不对,原因是我用的播放器只能播放 packed类型pcm数据,所以做了planar-->packed类型转换,将AV_SAMPLE_FMT_FLTP planar的样本格式转成AV_SAMPLE_FMT_S32 packed 类型的。
  2. 有杂音,原因是音频原样本格式是AV_SAMPLE_FMT_FLTP,float类型 32位,而我用的opensl播放,只支持int类型的样本,所以需要转换成32位的int类型 ,即AVSampleFormat::AV_SAMPLE_FMT_S32。

代码如下

int YaoAVFrame::getAudioPackedData(unsigned char * data){
    //每个样本的字节数 * 每个声道的样本数 * 声道数
    int bufferSize =  getPerSampleSize() * getNBSamples() * getChannels();
    if(data == nullptr){
        return bufferSize;
    }

    // 判断是 Packed 还是 Plane
    int isPanar = av_sample_fmt_is_planar((AVSampleFormat)imp->frame->format);
    if(isPanar){
        //EyerLog("Planarn");
        SwrContext * swrCtx = swr_alloc_set_opts(
                NULL,
                imp->frame->channel_layout,
                // av_get_packed_sample_fmt((AVSampleFormat)imp->frame->format),
                AVSampleFormat::AV_SAMPLE_FMT_S32,
                imp->frame->sample_rate,

                imp->frame->channel_layout,
                (AVSampleFormat)imp->frame->format,
                imp->frame->sample_rate,

                0,
                NULL
        );


        swr_init(swrCtx);

        int ret = swr_convert(swrCtx, &data, imp->frame->nb_samples, (const uint8_t **)imp->frame->data, imp->frame->nb_samples);

        swr_free(&swrCtx);
    }
    else{
        //EyerLog("Packedn");
        memcpy(data, imp->frame->data[0], bufferSize);
    }

    return 0;
}

完整代码:https://github.com/yinhuiyao11/YaoPlayerAndroid.git