Android中间层分析2.【media】音视频基础知识-4.ffmpeg pcm输出

开发环境vs2010 环境比较老。一下程序要求输出一个pcm数据,使用pcm工具可以打开播放。在这里简单介绍ffmpeg的api调用。后面还会写个整个audio的播放,会提供统一的工程。

c

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进行初始化。并且av_find_stream_info找到相关的信息。
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);
	
  • 准备输出了,准备输出的包(packet)和输出参数设置 和缓存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);
  • 关闭改关闭、释放改释放的资源。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沈万三djh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值