1. 程式人生 > 實用技巧 >FFMpeg音訊混合,背景音(二):pcm壓縮為aac整體流程

FFMpeg音訊混合,背景音(二):pcm壓縮為aac整體流程

一、整體流程程式碼

1、基本流程

#include<iostream>
using namespace std;
//用到的C的標頭檔案
extern "C"
{
#include<libavcodec/avcodec.h>
#include<libavformat/avformat.h>
#include<libavutil/avutil.h>
#include<libswresample/swresample.h>
}
//對用到的預編譯
#pragma comment(lib, "avformat.lib")
#pragma comment(lib, "avcodec.lib")
#pragma
comment(lib, "avutil.lib") #pragma comment(lib, "swresample.lib") int main() { //註冊 av_register_all(); avcodec_register_all(); //定義檔案 char inputFile[] = "audio.pcm"; char outputFile[] = "audio.aac"; int ret = 0; //找到aac編碼器 AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_AAC);
if (!codec) { cout << "avcodec_find_encoder faild" << endl; return -1; } //配置編碼器上下文 AVCodecContext* ac = avcodec_alloc_context3(codec); if (!ac) { cout << "avcodec_alloc_context3 faild" << endl; return -1; } //給編碼器設定引數
ac->sample_rate = 44100; //取樣率 ac->channels = 2; //聲道數 ac->channel_layout = AV_CH_LAYOUT_STEREO; //立體聲 ac->sample_fmt = AV_SAMPLE_FMT_FLTP; //取樣格式為32位float即樣本型別fltp ac->bit_rate = 64000; //位元率,取樣率。 //給音訊的幀設定同一個頭部 ac->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; //開啟音訊編碼器 ret = avcodec_open2(ac, codec, NULL); if (ret < 0) { cout << "avcodec_open2 faild" << endl; return -1; } //建立一個輸出的上下文, 初始化oc AVFormatContext *oc = NULL; avformat_alloc_output_context2(&oc, NULL, NULL, outputFile); if (!oc) { cout << " avformat_alloc_output_context2 faild" << endl; return -1; } //設定音訊流 AVStream* st = avformat_new_stream(oc, NULL); st->codecpar->codec_tag = 0; avcodec_parameters_from_context(st->codecpar,ac); //把ac引數拷貝過來 //類似於print,列印視訊或者音訊資訊,引數分別為輸出上下文,音視訊(0,1),輸出檔名,是否輸出 av_dump_format(oc, 0,outputFile, 1); //開啟檔案流 ret = avio_open(&oc->pb, outputFile, AVIO_FLAG_WRITE); if (ret < 0) { cout << "avio_open faild" << endl; return -1; } //開啟檔案IO流 avio_close(oc->pb); //關閉編碼器 avcodec_close(ac); avcodec_free_context(&ac); avformat_free_context(oc); return 0; }