FFMPEG系列课程(一)打开视频解码器
测试环境:windows10
开发工具:VS2013
从今天开始准备些FFmpeg的系列教程,今天是第一课我们研究下打开视频文件和视频解码器。演示环境在windows上,在Linux上代码也是一样。
windows上可以不编译ffmpeg源码,后面我会分别讲解在linux和在windows上如何编译ffmpeg,直接在FFmpeg官网下载已经编译好的dll和lib文件,下载地址https://ffmpeg.zeranoe.com/builds/ 或者www.ffmpeg.club 里面有32位和64位的,我下载的32位。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | //引用ffmpeg头文件,我这边是C++必须加上extern "C",ffmpeg都是c语言函数, //不加会链接失败,找不到定义 extern "C" { #include<libavformat/avformat.h> } //引用lib库,也可以在项目中设置,打开视频只需要用到这三个库 #pragma comment(lib,"avformat.lib") #pragma comment(lib,"avutil.lib") #pragma comment(lib,"avcodec.lib") #include <iostream> using namespace std; int main( int argc, char *argv[]) { //初始化所以ffmpeg的解码器 av_register_all(); char path[1024] = "video.mp4" ; //用来存放打开的视频流信息 AVFormatContext *ic = NULL; //用来存储视频流索引 int videoStream = 0; //打开视频播放流 //path参数表示打开的视频路径,这个路径可以包括各种视频文件 //也包括rtsp和http网络视频流 //第三个参数表示传入的视频格式,我这边不传递有FFmpeg内部获取 //最后一个参数是设置,我们这里也不传递 int re = avformat_open_input(&ic, path, 0, 0); if (re != 0) { //获取到FFmpeg的错误信息 char errorbuf[1024] = {0}; av_strerror(re, errorbuf, sizeof (errorbuf)); printf ( "open %s failed: %s\n" , path, errorbuf); return -1; } //遍历视频流,里面包含音频流,视频流,或者字母流,我们这里只处理视频 for ( int i = 0; i < ic->nb_streams; i++) { AVCodecContext *enc = ic->streams[i]->codec; //确认是视频流 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) { //存放视频流索引,后面的代码要用到 videoStream = i; //找到解码器,比如H264,解码器的信息也是ffmpeg内部获取的 AVCodec *codec = avcodec_find_decoder(enc->codec_id); if (!codec) { printf ( "video code not find!\n" ); return -2; } //打开视频解码器,打开音频解码器用的也是同一个函数 int err = avcodec_open2(enc, codec, NULL); if (err != 0) { char buf[1024] = { 0 }; av_strerror(err, buf, sizeof (buf)); printf (buf); return -3; } } } } |
其他的视频教程资料可以参考
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步