/** 获取MP4文件时长,ffmpeg库实现 */
int record::getMP4_duration_ffmpeg(const char *filename,long long *seconds)
{
if(filename == NULL)
{
printf("getMp4_duration_filename erro");
return -1;
}
AVFormatContext *ifmt_ctx = NULL; // 输入文件的demux
int videoindex = -1; // 视频索引
int audioindex = -1; // 音频索引
// 打开文件,主要是探测协议类型,如果是网络文件则创建网络链接
int ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL);
if (ret < 0) //如果打开媒体文件失败,打印失败原因
{
char buf[1024] = { 0 };
av_strerror(ret, buf, sizeof(buf) - 1);
printf("open %s failed:%s\n", filename, buf);
goto failed;
}
ret = avformat_find_stream_info(ifmt_ctx, NULL); //获取音视频文件信息
if (ret < 0) //如果打开媒体文件失败,打印失败原因
{
char buf[1024] = { 0 };
av_strerror(ret, buf, sizeof(buf) - 1);
printf("avformat_find_stream_info %s failed:%s\n", filename, buf);
goto failed;
}
//打开媒体文件成功
printf("\n==== av_dump_format filename:%s ===\n", filename);
av_dump_format(ifmt_ctx, 0, filename, 0);
// url: 调用avformat_open_input读取到的媒体文件的路径/名字
printf("media name:%s\n", ifmt_ctx->url);
// bit_rate: 媒体文件的码率,单位为bps
printf("media average bit_rate:%lldkbps\n",(int64_t)(ifmt_ctx->bit_rate/1024));
// 时间
long long total_seconds;
// duration: 媒体文件时长,单位微妙
total_seconds = (ifmt_ctx->duration) / AV_TIME_BASE; // 1000us = 1ms, 1000ms = 1秒
*seconds = total_seconds;
//通过上述运算,可以得到媒体文件的总时长
failed:
if(ifmt_ctx)
avformat_close_input(&ifmt_ctx);
return 0;
}
上面的有的时候不管用
AVFormatContext *ifmt_ctx = NULL;
int videoindex = -1; // 视频索引
int audioindex = -1; // 音频索引
char buf[1024] = {0};
int total_ms;
// 打开文件,主要是探测协议类型,如果是网络文件则创建网络链接
int ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL);
if (ret < 0) //如果打开媒体文件失败,打印失败原因
{
memset(buf, 0, sizeof(buf));
av_strerror(ret, buf, sizeof(buf) - 1);
goto failed;
}
ret = avformat_find_stream_info(ifmt_ctx, NULL); //获取音视频文件信息
if (ret < 0) //如果打开媒体文件失败,打印失败原因
{
memset(buf, 0, sizeof(buf));
av_strerror(ret, buf, sizeof(buf) - 1);
goto failed;
}
//打开媒体文件成功
av_dump_format(ifmt_ctx, 0, filename, 0);
// url: 调用avformat_open_input读取到的媒体文件的路径/名字
// bit_rate: 媒体文件的码率,单位为bps
// duration: 媒体文件时长,单位微妙
*seconds = (ifmt_ctx->duration) * 1000 / AV_TIME_BASE; // 1000us = 1ms, 1000ms = 1秒 返回的是毫秒
failed:
if(ifmt_ctx)
avformat_close_input(&ifmt_ctx);
return 0;

1万+

被折叠的 条评论
为什么被折叠?



