#include "stdio.h"
#include "stdlib.h"
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libavutil/avutil.h"
int main(int argc, char **argv)
{
if(argc < 3)
{
printf("argc number is error\n");
return 0;
}
av_register_all();
AVCodecContext *encodecCtx = NULL;
AVCodec *encodec;
AVPacket enpacket;
AVFrame *avframe;
int gotframeptr;
int frame_size = 0;
int *samples = 0;
int SAMPLESIZE = 0;
encodec = avcodec_find_encoder(CODEC_ID_AAC);
if(!encodec)
{
fprintf(stderr, "Unsupported encodec!\n");
return -1;
}
encodecCtx= avcodec_alloc_context3(encodec);
encodecCtx->channels = 2;
encodecCtx->sample_fmt = AV_SAMPLE_FMT_S16;
encodecCtx->sample_rate = 44100;
encodecCtx->bit_rate = 128000;
encodecCtx->profile = FF_PROFILE_AAC_LOW;
encodecCtx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
if((avcodec_open2(encodecCtx, encodec, NULL) < 0))
{
fprintf(stderr, "can't open encodec!\n");
return -1;
}
FILE *fin = NULL;
fin = fopen(argv[1],"rb");
if(!fin)
{
printf("open fin file error\n");
return 0;
}
FILE *fout = NULL;
fout = fopen(argv[2],"a+");
if(!fout)
{
printf("open fout file error\n");
return 0;
}
avframe = avcodec_alloc_frame();
if (!avframe)
{
fprintf(stderr, "Could not allocate audio frame\n");
exit(1);
}
avframe->nb_samples = encodecCtx->frame_size;
avframe->format = encodecCtx->sample_fmt;
avframe->channel_layout = encodecCtx->channel_layout;
int buffer_size = av_samples_get_buffer_size(NULL, encodecCtx->channels,
encodecCtx->frame_size,
encodecCtx->sample_fmt, 0);
printf("--%d---%d\n",encodecCtx->frame_size,buffer_size);
samples = av_malloc(buffer_size);
if (!samples)
{
fprintf(stderr, "Could not allocate %d bytes for samples buffer\n",
buffer_size);
exit(1);
}
/* setup the data pointers in the AVFrame */
int ret = avcodec_fill_audio_frame(avframe, encodecCtx->channels, encodecCtx->sample_fmt,
(const uint8_t*)samples, buffer_size, 0);
if (ret < 0)
{
fprintf(stderr, "Could not setup audio frame\n");
exit(1);
}
//memset(out_buf,0,encodecCtx->frame_size*8);
int size;
int len;
int got_output;
av_init_packet(&enpacket);
enpacket.data = NULL;
enpacket.size = 0;
while(1)
{
size = fread(samples,1,buffer_size,fin);
if(size == 0)
{
printf("read elf\n");
break;
}
len = avcodec_encode_audio2(encodecCtx,&enpacket,avframe,&got_output);
printf("1111---%d__1111__%d1111__%d\n",size,len,enpacket.size);
if(got_output)
{
int num = fwrite(enpacket.data,1,enpacket.size,fout);
if(num == 0)
{
printf("write error\n");
sleep(1);
}
av_free_packet(&enpacket);
av_init_packet(&enpacket);
enpacket.data = NULL;
enpacket.size = 0;
printf("222222222222222222222222\n");
}
//memset(out_buf,0,FF_MIN_BUFFER_SIZE);
}
av_free_packet(&enpacket);
free(samples);
fclose(fout);
fclose(fin);
return 0;
}