前面讲了一下ffmpeg的一些基本概念(ffmpeg中的基本概念),这里说一下如何使用ffmpeg进行视频录制。
录制视频的基本步骤是:
1. 初始化ffmpeg的基本对象,并将这些对象关联起来,然后打开文件并写入文件头。
2. 编码视频,并将编码后数据存写到文件中。
3. 写入文件尾,并清理ffmpeg对象。
首先,需要初始化ffmpeg的一些对象,初始化的顺序为:
创建并初始化AVOutputFormat, 基于AVOutputFormat创建并初始化AVFormatContext。
然后查找AVCodec, 基于找到的AVCodec创建并初始化AVCodecContext,打开AVCodec。
然后基于找到的AVCodec创建AVStream。
然后创建并初始化AVIOContext。
其中AVStream, AVCodec, AVCodecContext可能会有两组,一组用来录制音频,一组用来录制视频,如下:
AVOutputFormat和AVFormatContext可以通过avformat_alloc_output_context函数来初始化。
AVCodec通过avcodec_find_encoder函数来查找
AVCodecContext通过avcodec_alloc_context3来分配
AVCodecContext初始化完成后,可以通过avcodec_open2打开编码器
AVStream通过avformat_new_stream来分配
以上对象初始化完成后,需要将codec的信息拷贝到AVFormatContext对象中,以便与将编码器信息存储到文件中,这个操作可以通过avcodec_parameters_from_context操作
最后通过avio_open打开文件并初始化AVIOContext。
最后通过avformat_write_header写入文件头,整个初始化阶段就算是完成了
以下初始化代码供参考:
1 avformat_alloc_output_context2(&format_context_, nullptr, nullptr, file_path.c_str()); 2 if(format_context_ == nullptr){ 3 avformat_alloc_output_context2(&format_context_, nullptr, "mpeg", file_path.c_str()); 4 } 5 6 if(format_context_ == nullptr){ 7 return false; 8 } 9 10<