【开发心得】高效准确的利用ffmpeg-ffprobe 获取视频时长

1.ffmpeg解析时长的方案有多种,可以借助本身ffmpeg的能力解析,亦或者使用ffprobe解析时长,并且后者的解析效率更高。

解析命令参考:

/usr/bin/ffprobe http://ip/2017/06/27/084810_1012730.ts

解析结果截图:

编码思路:

使用java.lang.Runtime 执行shell命令(也可以使用apache commons exec 工具类)

方法参考:

public static String execDos(String dos) {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec(dos);
            process.waitFor();
            InputStream in = process.getErrorStream();
            return IOUtils.toString(in, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

分析执行结果,获得时长信息:

  String dosText = execDos(dos);
        log.info("耗时:" + (System.currentTimeMillis() - time) + "毫秒");
        log.info("dosText:" + dosText);
        int index = dosText.indexOf("Duration:");
        int startIndex = index + "Duration:".length();
        int endIndex = dosText.indexOf(",", index);
        String durationText = dosText.substring(startIndex, endIndex).trim();
        log.info("视频时长:" + durationText);
        String[] arr = durationText.split(":|\\.");
        if (arr.length == 4) {
            // 转换为秒
            duration = Integer.parseInt(arr[0]) * 3600.00 + Integer.parseInt(arr[1]) * 60.00 + Integer.parseInt(arr[2]) * 1.00 + Integer.parseInt(arr[3]) * 0.01;
        } else if (arr.length == 3) {
            // 转换为秒
            duration = Integer.parseInt(arr[0]) * 3600.00 + Integer.parseInt(arr[1]) * 60.00 + Integer.parseInt(arr[2]) * 1.00;
        }

end

猜你喜欢

转载自blog.csdn.net/qq_26834611/article/details/111568099