您的位置:首页 > 其它

ffmpeg 实现音频aac编码

2013-12-23 00:16 573 查看
1、编译ffmepg

./configure --disable-yasm --enable-nonfree --enable-libfaac --prefix=/home/ffmpeg/1_ffmpeg-2.1.1/install

2、编译audio_enc.c

makefile:

#!/bin/sh
INCLUDE = ../include
LIB_DIR = ../lib
LDFLAGS =  -lfaac -lavcodec -lavformat -lavdevice -lavfilter -lavutil -lswresample -pthread  -ldl -lswscale -lasound -lz -lm -lbz2

SRC=audio_enc.c
all:$(SRC)
gcc -g -Wall $(SRC) -o target -I $(INCLUDE) -L $(LIB_DIR) $(LDFLAGS)


注意:在这里编译的时候需要加上aac库,可能会找不到库函数undefined reference to `faacEncEncode'等

程序运行时,需要提供一个和程序参数一致的wav音频文件:

/*
* Copyright(C), 2013, Ubuntu Inc.
* File name:		audio_enc.c
* Author:     		xubinbin 徐彬彬 (Beijing China)
* Version:   		1.0
* Date: 			2013.12.23
* Description:		Use ffmpeg achieve aac audio coding.
* Function List:
* Email:			xubbwd@gmail.com
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#include <libavutil/opt.h>
#include <libavutil/mathematics.h>
#include <libavformat/avformat.h>

FILE * fp_in = NULL;
FILE * fp_out = NULL;

static int frame_count;

int main(int argc, char **argv)
{
int ret;
AVCodec *audio_codec;
AVCodecContext *c;
AVFrame *frame;
AVPacket pkt;
int got_output;

/* Initialize libavcodec, and register all codecs and formats. */
av_register_all();
avcodec_register_all();
//avdevice_register_all();

audio_codec = avcodec_find_encoder(AV_CODEC_ID_AAC);
c = avcodec_alloc_context3(audio_codec);

c->codec_id = AV_CODEC_ID_AAC;
c->sample_fmt = AV_SAMPLE_FMT_S16;
c->sample_rate = 44100;
c->channels = 2;
c->channel_layout = AV_CH_LAYOUT_STEREO;
c->bit_rate = 64000;

/* open the codec */
ret = avcodec_open2(c, audio_codec, NULL);
if (ret < 0) {
fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
exit(1);
}

/* allocate and init a re-usable frame */
frame = avcodec_alloc_frame();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
exit(1);
}

frame->nb_samples = c->frame_size;
frame->format = c->sample_fmt;
frame->channels = c->channels;
frame->channel_layout = c->channel_layout;
frame->linesize[0] = 4096;
frame->extended_data = frame->data[0] = av_malloc((size_t)frame->linesize[0]);

av_init_packet(&pkt);

fp_in = fopen("in.wav","rb");
fp_out= fopen("out.aac","wb");

//printf("frame->nb_samples = %d\n",frame->nb_samples);

while(1)
{
frame_count++;
bzero(frame->data[0],frame->linesize[0]);
ret = fread(frame->data[0],frame->linesize[0],1,fp_in);
if(ret <= 0)
{
printf("read over !\n");
break;
}
ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
exit(1);
}

if(got_output > 0)
{
//printf("pkt.size = %d\n",pkt.size);
fwrite(pkt.data,pkt.size,1,fp_out);
av_free_packet(&pkt);
}

#if 0
if(frame_count > 10)
{
printf("break @@@@@@@@@@@@\n");
break;
}
#endif
}

avcodec_close(c);
av_free(c);
avcodec_free_frame(&frame);

fclose(fp_in);
fclose(fp_out);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: