ffmepg是音视频解码的主流技术,为了满足项目需要,对ffmpeg进行入门学习,直接上代码。
首先,下载最新版本的ffmepg4.0,进行编译,以下代码使用ffmpeg4.0进行编译链接。
test.cpp
extern "C"
{
#include <libavcodec/avcodec.h>#include <libavformat/avformat.h>
}
#include <stdio.h>
#include <stdlib.h>
//#include <libswscale/swscale.h>
int main(int argc, char* argv[])
{
AVFormatContext *pFormatContext = NULL;
if(argc<2)
{
//ShowUseage(argv[0]);
return -1;
}
char *filepath = argv[1];
av_register_all();
//pFormatContext = avformat_alloc_context();
if(avformat_open_input(&pFormatContext,filepath,NULL,NULL)!=0) //Open the media file and read the header
{
printf("Can not open the media file you specified!\n");
return -1;
}
if(avformat_find_stream_info(pFormatContext, NULL)<0)
return -1; // Couldn't find stream information
printf("****************file information*****************\n");
av_dump_format(pFormatContext,0,filepath,0); //dump input information to the stdio
printf("*************************************************\n");
avformat_close_input(&pFormatContext);
return 0;
}
编译指令:
gcc -o test test.cpp -L/usr/local/ffmpeg4.0/lib -lm -lavdevice -lavformat -lavfilter -lavcodec -lswresample -lswscale -lavutil
编译过程中遇到的问题:
1. 由于拷贝的网上和example中的例子,不能编译通过,上网搜索,有人提出ffmpeg使用C语言开发应用头文件需添加 extern "C" {}
ffmpeg使用的基本流程:
1.声明变量 AVFormatContext *pFormatContext = NULL;
2. 初始化 av_register_all();
3. 打开媒体文件,并读取头文件 avformat_open_input
4. 读取流的信息 avformat_find_stream_info
5. ffmepg提供了av_dump_format方法打印媒体信息。
6. 关闭打开的文件 avformat_close_input()
这样就基本完成了一个基本的入门流程,初始化、打开媒体,读取媒体头文件、读取媒体信息、打印媒体信息、关闭媒体。