1. 程式人生 > >從AVFrame中取出音訊裸資料到一個buffer中

從AVFrame中取出音訊裸資料到一個buffer中

      在ffmpeg,音訊資料會儲存在AVFrame中extended_data陣列中,如果是打包模式(packed),就只用extended_data[0];如果是planar模式,則每個channel分別儲存在extended_data[i]中。對於音訊,只有linesize[0]有效,打包模式儲存整個音訊幀的buff大小,planar模式儲存每個channel的buff大小。

ffmpeg中對兩種模式(planar和packed)的說明(在samplefmt.h中有詳細說明):   

 * For planar sample formats, each audio channel is in a separate data plane,

 * and linesize is the buffer size, in bytes, for a single plane. All data

 * planes must be the same size. For packed sample formats, only the first data

 * plane is used, and samples for each channel are interleaved. In this case,

 * linesize is the buffer size, in bytes, for the 1 plane.

下面的例子是從解碼後得到的AVframe中,取出AV_SAMPLE_FMT_FLTP格式、2聲道資料的方法

// 得到該種格式資料一個buffer所需的空間大小
int data_size =av_samples_get_buffer_size(pFrame->linesize,decode_audioCodecCtx->channels,pFrame->nb_samples,AV_SAMPLE_FMT_FLTP, 0);

uint8_t *data = (uint8_t *)malloc(data_size);

memset(data, 0, data_size);

uint8_t *sample_buffer_L = pFrame->extended_data[0];//存放著左聲道的資料

uint8_t *sample_buffer_R = pFrame->extended_data[1];//存放著右聲道的資料</span></span>

兩者都是16bit,而裸的PCM檔案裡的資料是按照 LRLRLRLR  這樣儲存的,所以我們需要按照這種格式儲存16bit的資料:

for(int i = 0, j = 0; i < data_size; i += 4, j++){
    data[i] = sample_buffer_L[j] & 0xff;//左聲道低8位
    data[i+1] = (sample_buffer_L[j]>>8) & 0xff;//左聲道高8位
    data[i+2] = sample_buffer_R[j] & 0xff;//右聲道低8位
    data[i+3] = (sample_buffer_R[j]>>8) & 0xff;//右聲道高8位
}