简单写个程序获取视频的时长,以便做视频播放器的进度条。
很简单,头文件我懒的敲了,直接复制别的,所以有些多余。
代码如下:
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
#include <libavutil/avstring.h>
#include <libavutil/opt.h>
#include <libavutil/time.h>
#include <libavdevice/avdevice.h>
int main(int argc,char *argv[])
{
AVFormatContext *pFormatCtx = NULL;
int times;
av_register_all();
avformat_network_init();
if(avformat_open_input(&pFormatCtx,argv[1],NULL,NULL) !=0 )
//if(avformat_open_input(&pFormatCtx, "http://vfx.mtime.cn/Video/2019/01/15/mp4/190115161611510728_480.mp4", NULL, NULL)!=0)
//if(avformat_open_input(&pFormatCtx, "/home/llw/Desktop/output.mp4", NULL, NULL)!=0)
{
fprintf(stderr,"err!");
exit(1);
}
times = pFormatCtx->duration/1000000; //duration单位是us,转化为秒
printf("time:%d\n",times);
avformat_close_input(&pFormatCtx); //释放动作
return 0;
}
看图:
可以看到获取到了视频的时长,分别是145秒和254秒。
用别的播放器打开看看验证是否正确:
可以看到时间为4分14,对应上面的254秒。
程序OK!