開發(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);
- 關(guān)閉改關(guān)閉、釋放改釋放的資源。
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.1 音視頻基礎(chǔ)知識
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.2 需要認(rèn)識的一些工具
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.3 主流的開源項(xiàng)目
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.4 ffmpeg pcm輸出
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.5 ffmpeg yuv輸出
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.6 ffmpeg 簡單視頻播放器
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.7 Android最簡單的音頻播放器
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.8 Android最簡單的音頻播放器
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.9 Android最簡單的視頻播放器
Android 音視頻學(xué)習(xí)基礎(chǔ)--1.10 Android自制簡單音視頻播放器