Android 音視頻學(xué)習(xí)基礎(chǔ)--1.4 ffmpeg pcm輸出

開發(fā)環(huán)境vs2010 環(huán)境比較老。一下程序要求輸出一個pcm數(shù)據(jù),使用pcm工具可以打開播放。在這里簡單介紹ffmpeg的api調(diào)用。后面還會寫個整個audio的播放,會提供統(tǒng)一的工程。

AVFormatContext *pFormatCtx;
int             i, audioStream;
AVCodecContext  *pCodecCtx;
AVCodec         *pCodec;
  • 首先定義一些變量。
char url[]="WavinFlag.aac";
av_register_all();
avformat_network_init();
pFormatCtx = avformat_alloc_context();

if(avformat_open_input(&pFormatCtx,url,NULL,NULL)!=0){
    printf("Couldn't open input stream.\n");
    return -1;
}

if(av_find_stream_info(pFormatCtx)<0){
    printf("Couldn't find stream information.\n");
    return -1;
}
  • 然后對ffmpeg進(jìn)行初始化。并且av_find_stream_info找到相關(guān)的信息。
audioStream=-1;
for(i=0; i < pFormatCtx->nb_streams; i++)
    if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO){
        audioStream=i;
        break;
    }
  • 找到audio流編號。
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL){
    printf("Codec not found.\n");
    return -1;
}
  • 找到audio解碼器
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0){
    printf("Could not open codec.\n");
    return -1;
}
  • 打開這個解碼器
FILE *pFile=NULL;
pFile=fopen("output.pcm", "wb");
  • 定義一個pcm輸出的file。
AVPacket *packet=(AVPacket *)malloc(sizeof(AVPacket));
av_init_packet(packet);


uint64_t out_channel_layout=AV_CH_LAYOUT_STEREO;
int out_nb_samples=1024;
AVSampleFormat out_sample_fmt=AV_SAMPLE_FMT_S16;
int out_sample_rate=44100;
int out_channels=av_get_channel_layout_nb_channels(out_channel_layout);

int out_buffer_size=av_samples_get_buffer_size(NULL,out_channels ,out_nb_samples,out_sample_fmt, 1);

uint8_t *out_buffer=(uint8_t *)av_malloc(MAX_AUDIO_FRAME_SIZE*2);
    
  • 準(zhǔn)備輸出了,準(zhǔn)備輸出的包(packet)和輸出參數(shù)設(shè)置 和緩存buff。
AVFrame *pFrame;
pFrame=avcodec_alloc_frame();
  • 開始輸出拿出,先拿到指針。
while(av_read_frame(pFormatCtx, packet)>=0){
    if(packet->stream_index==audioStream){
        ret = avcodec_decode_audio4( pCodecCtx, pFrame,&got_picture, packet);
        if ( ret < 0 ) {
            printf("Error in decoding audio frame.\n");
            return -1;
        }
        if ( got_picture > 0 ){
            swr_convert(au_convert_ctx,&out_buffer, MAX_AUDIO_FRAME_SIZE,(const uint8_t **)pFrame->data , pFrame->nb_samples);

            fwrite(out_buffer, 1, out_buffer_size, pFile);//寫pcm文件,主意pcm的格式

            
            index++;
        }

    av_free_packet(packet);
}
  • 瘋狂輸出,和寫文件。
swr_free(&au_convert_ctx);

av_free(out_buffer);

avcodec_close(pCodecCtx);

av_close_input_file(pFormatCtx);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容