ffmpeg获取文件时长

/** 获取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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值