点击下边那个链接会转到github
下载完成后,添加include、lib到工程。
添加头文件:
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavformat/avio.h"
#include "libswscale/swscale.h"
}
代码:
AVDictionary* options = NULL;
av_dict_set(&options, "buffer_size", "1024000", 0); //设置缓存大小,1080p可将值跳到最大
av_dict_set(&options, "rtsp_transport", "tcp", 0); //以tcp的方式打开,
av_dict_set(&options, "stimeout", "5000000", 0); //设置超时断开链接时间,单位us
av_dict_set(&options, "max_delay", "500000", 0); //设置最大时延
AVFormatContext* pFormatCtx = avformat_alloc_context(); //用来申请AVFormatContext类型变量并初始化默认参数,申请的空间
//打开网络流或文件流
if (avformat_open_input(&pFormatCtx, pUrl, NULL, &options) != 0){
printf("Couldn't open input stream.\n");
return ;
}
//获取视频文件信息
if (avformat_find_stream_info(pFormatCtx, NULL) < 0){
printf("Couldn't find stream information.\n");
return ;
}
//查找码流中是否有视频流
int video_stream_index = -1;
for (int i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
video_stream_index = i;
}
}
if (video_stream_index == -1) {
printf("video_stream_index = -1\n");
return;
}
AVPacket* packet = (AVPacket*)av_malloc(sizeof(AVPacket)); // 申请空间,存放的每一帧数据 (h264、h265)
FILE* pFile = fopen("test.h265", "wb");
//
while (true){
if (av_read_frame(pFormatCtx, packet) >= 0){
if (packet->stream_index == video_stream_index){
fwrite(packet->data, 1, packet->size, pFile);
}
av_packet_unref(packet);
}
}
fclose(pFile);
av_free(packet);
avformat_close_input(&pFormatCtx);