天天看點

ffmpeg4.0.2實作音頻pcm轉aac編碼器

     在ffmpeg版本的飛速更新中,也給衆流媒體開發者們帶來堅實的瓶頸,最近做了一份仍使用ffmpeg4.0.2的libfaac實作pcm轉aac編碼器。據衆道友回報,光代碼已經不能滿足修煉需求,特奉上工程連接配接 https://download.csdn.net/download/guhongzhanchi/10815554

,誤了衆道友的修行,貧道在此特意聲明,概不負責也,因為負不起也。衆道友切莫歡喜過度,工程中可以編碼成aac,但卻出現了規律的“咔咔”聲,因為各類因素的原因,我就沒去深入解決,如有道友願不吝賜教,貧道銘感五内!

    言歸正傳,其實就是在原有的編碼流程上增加下音頻重采樣。在

fread()之前先初始化下      
ffmpeg4.0.2實作音頻pcm轉aac編碼器
SwrContext      
ffmpeg4.0.2實作音頻pcm轉aac編碼器
//格式轉換:pcm(s16)轉aac(fltp)
    //asfmt = aacc->sample_fmts;
    swr_ctx = swr_alloc_set_opts(nullptr, aacctx->channel_layout, aacctx->sample_fmt,aacctx->sample_rate,
                                 aacctx->channel_layout, psfmt, aacctx->sample_rate, 0, nullptr);
    if (swr_ctx == nullptr)
    {
        fprintf(stderr, "Could not allocate resample context!\n");
        return -1;
    }
    if (swr_init(swr_ctx) < 0)
    {
        fprintf(stderr, "Failed to initialize the resampling context!\n");
        return -1;
    }      
ffmpeg4.0.2實作音頻pcm轉aac編碼器

然後在fread()之後和

avcodec_send_frame()之前      
ffmpeg4.0.2實作音頻pcm轉aac編碼器
swr_convert()      
ffmpeg4.0.2實作音頻pcm轉aac編碼器
if (swr_convert(swr_ctx, aacfr->extended_data, aacfr->nb_samples, (const uint8_t**)aacfr->data, aacfr->nb_samples) <= 0)
        {
            cout << "Audio swr_convert failed!" << endl;
            return -1;
        }      
ffmpeg4.0.2實作音頻pcm轉aac編碼器

對此就可以編碼了。

      我這裡出現了規律的"咔咔“雜音,有道友說是aac的buffer小了,我增加了4倍依然沒解決

aacSize = av_samples_get_buffer_size(NULL, aacctx->channels,aacctx->frame_size,aacctx->sample_fmt, 1);
    aacfrBuf = (uint8_t *)av_malloc(aacSize * 4);      
ffmpeg4.0.2實作音頻pcm轉aac編碼器

也有道友說編碼時幀跟不上。從資料上分析bug我也覺得這個原因很有可能,但後來在仔細檢查重采樣傳參後發現參數傳錯了,修完這個bug就可以正常編碼,隻是目前不支援解碼?各位要有見解,敬請留言。

繼續閱讀