使用ffmpeg获取视频时长等

查看视频信息的命令:ffmpeg -i 视频文件,如下:

ffmpeg -i d://a.mp4

控制台输出

ffmpeg version N-89471-g88e2dc7d04 Copyright (c) 2000-2017 the FFmpeg developers

  built with gcc 7.2.0 (GCC)
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --e
nable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libblur
ay --enable-libfreetype --enable-libmp3lame --enable-libopenjpeg --enable-libopu
s --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --ena
ble-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-lib
x264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-z
lib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-amf --enable-cu
da --enable-cuvid --enable-d3d11va --enable-nvenc --enable-dxva2 --enable-avisyn
th --enable-libmfx
  libavutil      56.  5.100 / 56.  5.100
  libavcodec     58.  6.103 / 58.  6.103
  libavformat    58.  3.100 / 58.  3.100
  libavdevice    58.  0.100 / 58.  0.100
  libavfilter     7.  7.100 /  7.  7.100
  libswscale      5.  0.101 /  5.  0.101
  libswresample   3.  0.101 /  3.  0.101
  libpostproc    55.  0.100 / 55.  0.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'd://a.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : www.aliyun.com - Media Transcoding
  Duration: 00:05:29.20, start: 0.000000, bitrate: 377 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360,
340 kb/s, 20 fps, 20 tbr, 10240 tbn, 40 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, flt
p, 31 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
At least one output file must be specified

关键是这一句,包含了视频时长、开始时间与比特率

Duration: 00:05:29.20, start: 0.000000, bitrate: 377 kb/s

可以根据以下java代码来获取时长

import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TestMp4 {
    @Test
    public void test() {
        getVideoTime("d://c.wmv");
    }

    /**
     * 获取视频总时间
     */
    private void getVideoTime(String video_path) {
        List<String> commands = new ArrayList<>();
        commands.add("ffmpeg");
        commands.add("-i");
        commands.add(video_path);
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commands);
            Process p = builder.start();

            //从输入流中读取视频信息
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
            br.close();

            //从视频信息中解析时长
            String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
            Pattern pattern = Pattern.compile(regexDuration);
            Matcher m = pattern.matcher(stringBuilder.toString());
            if (m.find()) {
                int time = getTimelen(m.group(1));
                System.out.println("视频时长:" + time + "s , 开始时间:" + m.group(2) + ", 比特率:" + m.group(3) + "kb/s");
            }

            String regexVideo = "Video: (.*?), (.*?), (.*?)[,\\s]";
            pattern = Pattern.compile(regexVideo);
            m = pattern.matcher(stringBuilder.toString());
            if (m.find()) {
                System.out.println("编码格式:" + m.group(1) + ", 视频格式:" + m.group(2) + ", 分辨率:" + m.group(3) + "kb/s");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 格式:"00:00:10.68"
    private int getTimelen(String timelen) {
        int min = 0;
        String strs[] = timelen.split(":");
        if (strs[0].compareTo("0") > 0) {
            // 秒
            min += Integer.valueOf(strs[0]) * 60 * 60;
        }
        if (strs[1].compareTo("0") > 0) {
            min += Integer.valueOf(strs[1]) * 60;
        }
        if (strs[2].compareTo("0") > 0) {
            min += Math.round(Float.valueOf(strs[2]));
        }
        return min;
    }
}

输出

视频时长:329s , 开始时间:0.000000, 比特率:377kb/s
编码格式:h264 (High) (avc1 / 0x31637661), 视频格式:yuv420p, 分辨率:640x360kb/s

参考:http://liang100100.iteye.com/blog/2215439

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
FFmpeg中,获取视频时长可以通过AVFormatContext中的duration字段来实现,该字段表示音视频文件的总时长,单位是微秒(us)。如果duration为AV_NOPTS_VALUE,则表示无法获取时长。 具体实现代码如下: ```c AVFormatContext *fmt_ctx = NULL; if (avformat_open_input(&fmt_ctx, filename, NULL, NULL) != 0) { printf("Failed to open file '%s'\n", filename); return -1; } if (avformat_find_stream_info(fmt_ctx, NULL) < 0) { printf("Failed to retrieve input stream information\n"); return -1; } int64_t duration = fmt_ctx->duration; if (duration != AV_NOPTS_VALUE) { int hours, mins, secs, us; secs = duration / AV_TIME_BASE; us = duration % AV_TIME_BASE; mins = secs / 60; secs %= 60; hours = mins / 60; mins %= 60; printf("Duration: %02d:%02d:%02d.%02d\n", hours, mins, secs, (100 * us) / AV_TIME_BASE); } else { printf("Duration: N/A\n"); } avformat_close_input(&fmt_ctx); ``` 在这个例子中,我们首先使用avformat_open_input函数打开音视频文件,然后通过avformat_find_stream_info函数获取视频文件的流信息,接着获取AVFormatContext的duration字段,如果duration不为AV_NOPTS_VALUE,则表示获取到了时长,我们将其转换为时分秒的格式进行输出。最后,我们需要调用avformat_close_input函数关闭文件并释放资源。 需要注意的是,由于duration字段的单位是微秒,因此我们需要将其转换为秒,进而转换为时分秒格式。另外,如果获取时长失败,则duration的值将为AV_NOPTS_VALUE,我们需要做特殊处理。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值