编码流程
- 注册所有组件 av_register_all()
- 创建封装格式上下文 avformat_alloc_context() 返回一个AVFormatContext
- 初始化输入输出上下文(打开输出文件) avio_open(),可以输出到本地或者网络地址等等
- 创建媒体流 avformat_new_stream()
- 初始化编码器上下文以及设置参数 AVCodecContext
- 查找编码器 avcodec_find_encoder_by_name()
- 打开编码器 avcodec_open2()
- 写入头文件 avformat_write_header();
- 打开本地需要转换的文件 fopen(inFile, “rb”)
- 初始化 AVFrame,AVPacket
- 开始转换 avcodec_send_frame() avcodec_receive_packet()
- 开始写入本地 av_write_frame()
- 写入文件尾 av_write_trailer()
公共变量
AVCodec *avAudioCodec;
AVCodecContext *avAudioContext;
AVFrame *audioFrame;
AVPacket *audioPacket;
AVStream *audioStream;
int audioPts = 0;
AVFormatContext *formatContext;
int audioBufferSize;
uint8_t *outBuffer;
FILE *in_file;
初始化
int AudioVideoEncode::audioEncoderInit(JNIEnv *env) {
const char *outFile = "/sdcard/aaa/gjk.aac";
const char *inFile = "/sdcard/aaa/PCM/pcm.pcm";
av_register_all();
formatContext = avformat_alloc_context();
formatContext->oformat = av_guess_format(NULL, outFile, NULL);
if (avio_open(&formatContext->pb, outFile, AVIO_FLAG_READ_WRITE) < 0) return -1;
audioStream = avformat_new_stream(formatContext, 0);
if (audioStream == NULL) return -1;
avAudioContext = audioStream->codec;
avAudioContext->codec_id = formatContext->oformat->audio_codec;
avAudioContext->codec_type = AVMEDIA_TYPE_AUDIO;
avAudioContext->sample_fmt = AV_SAMPLE_FMT_S16;
avAudioContext->sample_rate = 8000;
avAudioContext->channel_layout = AV_CH_LAYOUT_MONO;
avAudioContext->channels = 1;
avAudioContext->bit_rate = 128000;
avAudioCodec = avcodec_find_encoder_by_name("libfdk_aac");
if (avAudioCodec == NULL) return -1;
int ret = avcodec_open2(avAudioContext, avAudioCodec, NULL);
if (ret < 0) return -1;
avformat_write_header(formatContext, NULL);
audioFrame = av_frame_alloc();
audioFrame->nb_samples = avAudioContext->frame_size;
audioFrame->format = avAudioContext->sample_fmt;
in_file = fopen(inFile, "rb");
if (in_file == NULL) return -1;
audioBufferSize = av_samples_get_buffer_size(NULL,
avAudioContext->channels,
avAudioContext->frame_size,
avAudioContext->sample_fmt,
1);
outBuffer = (uint8_t *) av_malloc(audioBufferSize);
avcodec_fill_audio_frame(audioFrame,
avAudioContext->channels,
avAudioContext->sample_fmt,
(const uint8_t *) outBuffer,
audioBufferSize,
1);
audioPacket = (AVPacket *) av_malloc(audioBufferSize);
audioPts = 0;
return 0;
}
开始编码
void AudioVideoEncode::audioEncoder(JNIEnv *env, jobject obj, jbyte *byte, int byteLength) {
int ret;
memcpy(audioFrame->data[0], buf, byteLength);
audioFrame->pts = audioPts;
audioPts++;
ret = avcodec_send_frame(avAudioContext, audioFrame);
if (ret < 0) return;
ret = avcodec_receive_packet(avAudioContext, audioPacket);
if (ret < 0) return;
audioPacket->stream_index = audioStream->index;
ret = av_write_frame(formatContext, audioPacket);
if (ret < 0) return;
LOGE("音频编码写入成功");
av_packet_unref(audioPacket);
}
写入文件尾
av_write_trailer(formatContext);