1. 程式人生 > >[SimplePlayer] 4. 從視訊檔案中提取音訊

[SimplePlayer] 4. 從視訊檔案中提取音訊

提取音訊,具體點來說就是提取音訊幀。提取方法與從視訊檔案中提取影象的方法基本一樣,這裡僅列出其中的不同點:

1. 由於目的提取音訊,因此在demux的時候需要指定的是提取audio stream

AudioStream = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);

 

2. 在decode時,解碼音訊與解碼視訊分別採用的是不同的API

avcodec_decode_audio4(pCodecCtx, pFrame, &frameFinished, &packet);

 

3. 由於本播放器的音訊輸出實現是基於SDL,而SDL支援輸出為S16的音訊樣本格式(也許是系統原因?),因此我們這裡在儲存檔案時,如果解碼出來的音訊樣本格式不是S16,那麼就需要對其進行格式轉換,以方便後續讀取檔案進行播放。下面以最常見的FLTP格式為例,把該格式的音訊轉換為S16格式的音訊。

    sample_count = pFrame->nb_samples;
    channel0 = (float *)pFrame->extended_data[0];
    channel1 = (float *)pFrame->extended_data[1];
    
    //normal PCM is mixed(interleave) track, but fltp "p" means planar
    if(pFrame->format == AV_SAMPLE_FMT_FLTP) 
    {
        for(i=0; i<sample_count; i++){ //stereo 
            sample0 = (short)(channel0[i]*32767.0f);
            sample1 = (short)(channel1[i]*32767.0f);
            fwrite(&sample0, 2, 1, pFile);
            fwrite(&sample1, 2, 1, pFile);
        }
    }