由文件得到的上下文就可以,如下:
AVFormatContext* pFormatCtx = NULL;
AVOutputFormat* fmt = NULL;
AVStream* audio_st = NULL;
AVCodecContext* pCodecCtx = NULL;
AVCodec* pCodec = NULL;
uint8_t* frame_buf = NULL;
AVFrame* frame = NULL;
int size;
const char* out_file = "test.aac";
av_register_all();
pFormatCtx = avformat_alloc_context();
fmt = av_guess_format(NULL, out_file, NULL);
pFormatCtx->oformat = fmt;
audio_st = avformat_new_stream(pFormatCtx, 0);
if (audio_st == NULL){
return -1;
}
pCodecCtx = audio_st->codec;
pCodecCtx->codec_id = fmt->audio_codec;
pCodecCtx->codec_id = AV_CODEC_ID_AAC;
printf("编码码器,AV_CODEC_ID_AAC:%u,%u\n", pCodecCtx->codec_id, AV_CODEC_ID_AAC);
pCodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
pCodecCtx->sample_fmt = AV_SAMPLE_FMT_S16;
pCodecCtx->sample_rate = 44100;
pCodecCtx->channel_layout = AV_CH_LAYOUT_STEREO;
pCodecCtx->channels = av_get_channel_layout_nb_channels(pCodecCtx->channel_layout);
printf("pCodecCtx->channels:%d\n", pCodecCtx->channels);
pCodecCtx->bit_rate = 64000;
//输出格式信息
av_dump_format(pFormatCtx, 0, out_file, 1);
pCodec = avcodec_find_encoder(AV_CODEC_ID_AAC);
if (!pCodec)
{
printf("没有找到合适的编码器!\n");
return -1;
}
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
{
printf("编码器打开失败!\n");
return -1;
}
printf("pCodecCtx->channels:%d, pCodecCtx->frame_size:%d, pCodecCtx->sample_fmt:%d\n", pCodecCtx->channels, pCodecCtx->frame_size, pCodecCtx->sample_fmt);
如果是自己分配的,如下:
<pre class="cpp" name="code">pCodec = avcodec_find_decoder(AV_CODEC_ID_AAC);
if (!pCodec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
pCodecCtx = avcodec_alloc_context3(pCodec);
if (!pCodecCtx) {
fprintf(stderr, "Could not allocate audio codec context\n");
exit(1);
}
pCodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
pCodecCtx->sample_fmt = AV_SAMPLE_FMT_S16;
pCodecCtx->bit_rate = 64000;
pCodecCtx->sample_rate = 44100;
pCodecCtx->frame_size = 1024;
pCodecCtx->channel_layout = AV_CH_LAYOUT_STEREO;
pCodecCtx->channels = av_get_channel_layout_nb_channels(pCodecCtx->channel_layout);
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
printf("pCodecCtx->sample_rate:%d\n", pCodecCtx->sample_rate);
printf("pCodecCtx->channels:%d, pCodecCtx->frame_size:%d, pCodecCtx->sample_fmt:%d\n", pCodecCtx->channels, pCodecCtx->frame_size, pCodecCtx->sample_fmt);
其中的指定pCodecCtx->sample_fmt = AV_SAMPLE_FMT_S16无效,自动变为 AV_SAMPLE_FMT_FLTP,后面编码也就会非法退出。