[Cmake-Android音視頻]ffmpeg3.4音頻重採樣

音頻重採樣流程圖

函數介紹

swr_alloc()

分配音頻重採樣的上下文

 

swr_alloc_set_opts(...)

設置音頻重採樣參數,可以通過音頻的樣本率來改變播放速度,但聲音一般會失真

struct SwrContext *swr_alloc_set_opts(struct SwrContext *s,
                                    int64_t out_ch_layout, 
                                    enum AVSampleFormat out_sample_fmt, 
                                    int out_sample_rate,
                                    int64_t  in_ch_layout, 
                                    enum AVSampleFormat  in_sample_fmt, 
                                    int  in_sample_rate,
                                    int log_offset, void *log_ctx);

參數說明:

  • 參數1:音頻重採樣上下文
  • 參數2:輸出的layout, 如:5.1聲道…
  • 參數3:輸出的樣本格式。Float, S16, S24,一般選用是s16  絕大部分聲卡支持
  • 參數4:輸出的樣本率。可以不變。
  • 參數5:輸入的layout。
  • 參數6:輸入的樣本格式。
  • 參數7:輸入的樣本率。
  • 參數8,參數9,日誌,不用管,可直接傳0

 

swr_init(struct SwrContext *s)

初始化音頻重採樣上下文

 

swr_convert(...)

對音頻幀進行重採樣

int swr_convert(struct SwrContext *s, uint8_t **out, int out_count,
                                const uint8_t **in , int in_count);

參數說明:

  • 參數1:音頻重採樣的上下文
  • 參數2:輸出的指針。傳遞的輸出的數組
  • 參數3:輸出的樣本數量,不是字節數。單通道的樣本數量。
  • 參數4:輸入的數組,AVFrame解碼出來的DATA
  • 參數5:輸入的單通道的樣本數量。

 

swr_free(struct SwrContext **s)

釋放音頻重採樣上下文空間

 

關鍵代碼參考

//音頻重採樣上下文初始化
SwrContext *swrContext = swr_alloc();
char *pcm = new char[480000*4*2];
swrContext = swr_alloc_set_opts(swrContext,
                                av_get_default_channel_layout(2),
                                AV_SAMPLE_FMT_S16,
                                ac->sample_rate,
                                av_get_default_channel_layout(ac->channels),
                                ac->sample_fmt,
                                ac->sample_rate,
                                0, 0);
re = swr_init(swrContext);
if (re != 0)
{
    LOGI("swr_init failed");
} else
{
    LOGI("swr_init success");
}
uint8_t *out[2] = {0};
out[0] = (uint8_t *)pcm;

//轉換音頻幀
int len = swr_convert(swrContext, out, frame->nb_samples,
                      (const uint8_t **)frame->data, frame->nb_samples);

 

注意:

音頻重採樣的相關函數包含在 libswresample.so 庫中

同時在代碼中包含頭文件 #include <libswresample/swresample.h> 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章