FFmpeg入门系列教程 (五)

PCM编码为AAC

    av_register_all():注册FFmpeg所有编解码器。

    avformat_alloc_output_context2():初始化输出码流的AVFormatContext。

    avio_open():打开输出文件。

    avcodec_find_encoder_by_name():查找编码器。

   av_new_stream():创建输出码流的AVStream。

    avcodec_open2():打开编码器。

    avformat_write_header():写文件头。

    avcodec_send_frame():编码一帧视频。即将AVFrame编码为AVPacket

   avcodec_receive_packet():接收编码后的数据

    av_write_frame():将编码后的视频码流写入文件。

    av_write_trailer():写文件尾。

#include <stdio.h>

extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include <libswresample/swresample.h>
//引入时间
#include "libavutil/time.h"
#include "libavutil/imgutils.h"
}


int main(int argc, char* argv[])
{
    AVFormatContext *pFormatCtx = NULL;
    AVOutputFormat *outfmt = NULL;
    AVStream *audio_stream = NULL;
    AVCodecContext *pCodecCtx = NULL;
    AVCodec *pCodec = NULL;
    uint8_t *frame_buf = NULL;
    AVFrame *frame = NULL;
    int size = 0;
    int ret = 0;

    FILE *in_file = fopen("ws.pcm", "rb");    //音频PCM采样数据
    const char *out_file = "ws.aac";                    //输出文件路径

    AVSampleFormat inSampleFmt = AV_SAMPLE_FMT_S16;
    AVSampleFormat outSampleFmt = AV_SAMPLE_FMT_S16;
    const int sampleRate = 44100;
    const int channels = 2;
    const int sampleByte = 2;
    int readSize = 0;

    av_register_all();

    avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
    outfmt = pFormatCtx->oformat;

    //open out file
    if (avio_open(&pFormatCtx->pb, out_file, AVIO_FLAG_READ_WRITE) < 0) {
        av_log(NULL, AV_LOG_ERROR, "%s", "输出文件打开失败!\n");
        return -1;
    }
    pCodec = avcodec_find_encoder_by_name("libfdk_aac");
    //pCodec = avcodec_find_encoder(AV_CODEC_ID_AAC);
    if (!pCodec)
    {
        av_log(NULL, AV_LOG_ERROR, "%s", "没有找到合适的编码器!");
        return -1;
    }
    //创建一路音频流
    audio_stream = avformat_new_stream(pFormatCtx, pCodec);
    if (audio_stream == NULL)
    {
        av_log(NULL, AV_LOG_ERROR, "%s", "avformat_new_stream error");
        return -1;
    }
    //设置编码器参数
    pCodecCtx = audio_stream->codec;
    pCodecCtx->codec_id = outfmt->audio_codec;
    pCodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
    pCodecCtx->sample_fmt = outSampleFmt;
    pCodecCtx->sample_rate = sampleRate;
    pCodecCtx->channel_layout = AV_CH_LAYOUT_STEREO;
    pCodecCtx->channels = av_get_channel_layout_nb_channels(pCodecCtx->channel_layout);
    pCodecCtx->bit_rate = 64000;

    //输出格式信息
    av_dump_format(pFormatCtx, 0, out_file, 1);
    //2 音频重采样 上下文初始化
    SwrContext *asc = NULL;
    asc = swr_alloc_set_opts(asc,
                             av_get_default_channel_layout(channels), outSampleFmt,
                             sampleRate,//输出格式
                             av_get_default_channel_layout(channels), inSampleFmt, sampleRate, 0,
                             0);//输入格式
    if (!asc)
    {
        av_log(NULL, AV_LOG_ERROR, "%s", "swr_alloc_set_opts failed!");
        return -1;
    }
    ret = swr_init(asc);
    if (ret < 0)
    {
        return ret;
    }

    //打开编码器
    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
    {
        av_log(NULL, AV_LOG_ERROR, "%s", "编码器打开失败!\n");
        return -1;
    }
    frame = av_frame_alloc();
    frame->nb_samples = pCodecCtx->frame_size;
    frame->format = pCodecCtx->sample_fmt;
    av_log(NULL, AV_LOG_DEBUG, "sample_rate:%d,frame_size:%d, channels:%d", sampleRate,
           frame->nb_samples, frame->channels);
    //编码每一帧的字节数
    size = av_samples_get_buffer_size(NULL, pCodecCtx->channels, pCodecCtx->frame_size,
                                      pCodecCtx->sample_fmt, 1);
    frame_buf = (uint8_t *) av_malloc(size);
    //一次读取一帧音频的字节数
    readSize = frame->nb_samples * channels * sampleByte;
    char *buf = new char[readSize];

    avcodec_fill_audio_frame(frame, pCodecCtx->channels, pCodecCtx->sample_fmt,
                             (const uint8_t *) frame_buf, size, 1);

    audio_stream->codecpar->codec_tag = 0;
    audio_stream->time_base = audio_stream->codec->time_base;
    //从编码器复制参数
    avcodec_parameters_from_context(audio_stream->codecpar, pCodecCtx);

    //写文件头
    avformat_write_header(pFormatCtx, NULL);
    AVPacket pkt;
    av_new_packet(&pkt, size);
    int apts = 0;

    for (int i = 0;; i++)
    {
        //读入PCM
        if (fread(buf, 1, readSize, in_file) < 0)
        {
            printf("文件读取错误!\n");
            return -1;
        }
        else if (feof(in_file))
        {
            break;
        }
        frame->pts = apts;
        //计算pts
        AVRational av;
        av.num = 1;
        av.den = sampleRate;
        apts += av_rescale_q(frame->nb_samples, av, pCodecCtx->time_base);
        //重采样源数据
        const uint8_t *indata[AV_NUM_DATA_POINTERS] = {0};
        indata[0] = (uint8_t *) buf;
        ret = swr_convert(asc, frame->data, frame->nb_samples, //输出参数,输出存储地址和样本数量
                          indata, frame->nb_samples
                          );
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "swr_convert error");
            return ret;
        }
        //编码
        ret = avcodec_send_frame(pCodecCtx, frame);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "avcodec_send_frame error\n");
            return ret;
        }
        //接受编码后的数据
        ret = avcodec_receive_packet(pCodecCtx, &pkt);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "avcodec_receive_packet!error \n");
            continue;
        }
        //pts dts duration转换为以audio_stream->time_base为基准的值。
        pkt.stream_index = audio_stream->index;
        pkt.pts = av_rescale_q(pkt.pts, pCodecCtx->time_base, audio_stream->time_base);
        pkt.dts = av_rescale_q(pkt.dts, pCodecCtx->time_base, audio_stream->time_base);
        pkt.duration = av_rescale_q(pkt.duration, pCodecCtx->time_base, audio_stream->time_base);
        ret = av_write_frame(pFormatCtx, &pkt);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "av_write_frame error!");
        }
        else
        {
            av_log(NULL, AV_LOG_DEBUG, " 第%d帧 encode success", i);
        }
        av_packet_unref(&pkt);
    }
    //写文件尾
    av_write_trailer(pFormatCtx);
    //清理
    avcodec_close(audio_stream->codec);
    av_free(frame);
    av_free(frame_buf);
    avio_close(pFormatCtx->pb);
    avformat_free_context(pFormatCtx);

    fclose(in_file);
    av_log(NULL, AV_LOG_DEBUG, "finish !");

    return 0;
}

下一篇将介绍一下 yuv文件编码为h264文件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容