java: 通过ffmpeg获取视频时长

0 引言

今天正好计划学习新的课程,因为是下载到本地的视频,为了方便做学习计划,要统计视频时长。不想一个一个的数,就利用ffmpeg做了一个视频时长统计以及自动分配每日学习任务的demo

以此记录方便后续参考

1 环境搭建

1.1 安装ffmpeg

1.1 下载ffmpeg

官方下载地址
请添加图片描述
请添加图片描述

1.2 双击可执行文件ffmpeg

请添加图片描述

1.3 查看版本

cd /Library/software/ffmpeg5.0
./ffmpeg -version

请添加图片描述

2 开发

1、创建springboot项目,修改配置文件

# 应用名称
spring:
  application:
    name: GetVideoTime
# 应用服务 WEB 访问端口
server:
  port: 8888

video:
  # 支持的视频格式,多个用,隔开
  suffix: .avi,.mp4,.flv,.wmv
  # ffmpeg路径,安装步骤参考doc/ffmpeg安装.md
  ffmpeg-path: /Library/software/ffmpeg5.0/ffmpeg

2、创建controller

/**
 * @author whx
 * @date 2022/2/8
 */
@RestController
@RequestMapping("video")
@AllArgsConstructor
public class VideoController {

    private final VideoService videoService;

    /**
     * 获取文件夹下视频总时长
     * @param path 文件路径
     * @return
     */
    @GetMapping("getTime")
    public R getTime(String path,Integer studyHour){
        return videoService.getVideoTimeFromPath(path,studyHour);
    }
}

3、创建返回数据实体类

@Data
@AllArgsConstructor
public class VideoTime {
    /**
     * 总时长
     */
    private String totalTime;
    /**
     * 时长明细 文件名-时长
     */
    private SortedMap<String,String> details;

    /**
     * 每日任务
     */
    private SortedMap<Integer, VideoTime> tasks;

    public VideoTime(String totalTime, SortedMap<String, String> details) {
        this.totalTime = totalTime;
        this.details = details;
    }
}

4、创建返回数据包装类

/**
 * 返回数据包装类
 * @author whx
 * @date 2022/2/8
 */
@Data
@AllArgsConstructor
public class R<T> {

    private int code;
    private String message;
    private T data;

    public static R success(){
        return new R(200,"操作成功",null);
    }

    public static R fail(String msg){
        return new R(500,msg,null);
    }

    public static <T>R data(T data){
        return new R(200,"操作成功",data);
    }
}

5、书写主业务代码

/**
 * @author whx
 * @date 2022/2/8
 */
@Service
@Slf4j
public class VideoServiceImpl implements VideoService {

    @Value("${video.suffix}")
    private List<String> videoSuffix;

    @Value("${video.ffmpeg-path}")
    private String ffmpegPath; 

    @Override
    public R getVideoTimeFromPath(String path,Integer studyHour) {
        if(studyHour == null){
            studyHour = 2;
        }
        File filePath = new File(path);
        if(filePath.exists()){
            List<File> files = FileUtil.getVideoFiles(filePath, videoSuffix);
            if(files.isEmpty()){
                return R.fail(String.format("%s 该路径下未找到视频文件,请检查路径是否有误或者是否在配置文件中配置视频格式",path));
            }
            TreeMap<String,String> details = new TreeMap<>();
            TreeMap<Integer,VideoTime> tasks = new TreeMap<>();
            TreeMap<String,String> taskDetails = new TreeMap<>();
            AtomicInteger index = new AtomicInteger(1);
            AtomicLong videoTime = new AtomicLong();
            long studyHourMilSecond = (long) studyHour * 3600 * 1000;
            long sum = 0;
            for (File file : files) {
                try {
                    long time = readVideoTimeFromCommand(file.getAbsolutePath(),ffmpegPath);
                    sum += time;
                    videoTime.addAndGet(time);
                    String detail = formatTime(time);
                    if(videoTime.longValue() < studyHourMilSecond){
                        taskDetails.put(file.getName(),detail);
                    }else{
                        tasks.put(index.intValue(),new VideoTime(formatTime(videoTime.longValue()),taskDetails));
                        videoTime.set(0);
                        index.incrementAndGet();
                        taskDetails = new TreeMap<>();
                        taskDetails.put(file.getName(),detail);
                    }
                    log.info(file.getName()+":"+detail);
                    details.put(file.getName(),detail);
                } catch (Exception e) {
                    log.error("获取视频时长失败:" + e.getMessage());
                    details.put(file.getName(),"获取失败");
                    e.printStackTrace();
                }
            }
            String sumStr = formatTime(sum);
            log.info("总时长:" + sumStr);
            return R.data(new VideoTime(sumStr,details,tasks));
        }
        return R.fail("%s 该路径不存在,请检查路径是否有误");
    }
}

6、获取视频文件方法

public class FileUtil {

    private static final File[] EMPTY_FILE_ARR = new File[0];
    /**
     * 获取文件夹下所有视频文件
     *
     * @param filePath
     * @param videoSuffix
     * @return
     */
    public static List<File> getVideoFiles(File filePath, List<String> videoSuffix) {
        if (filePath == null) {
            return new ArrayList<>();
        }
        List<File> allFile = new ArrayList<>();
        allFile.addAll(Arrays.asList(Optional.ofNullable(filePath.listFiles(file -> {
            if (!file.isDirectory()) {
                for (String suffix : videoSuffix) {
                    if (file.getPath().endsWith(suffix)) {
                        return true;
                    }
                }
            } else {
                allFile.addAll(getVideoFiles(file, videoSuffix));
            }
            return false;
        })).orElse(EMPTY_FILE_ARR)));
        return allFile;
    }
}

7、获取单个视频时长方法

public static long readVideoTimeFromCommand(String filePath, String ffmpegPath) throws IOException {
        ProcessBuilder builder = new ProcessBuilder();
        List<String> commands = new ArrayList<>();
        commands.add(ffmpegPath);
        commands.add("-i");
        commands.add(filePath);
        builder.command(commands);
        builder.redirectErrorStream(true);
        Process p = builder.start();
        // 获取执行输出信息
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder outInfo = new StringBuilder();
        String line = "";
        while ((line = br.readLine()) != null) {
            outInfo.append(line);
        }
        br.close();
        // 通过正则获取时长信息
        String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
        Pattern pattern = Pattern.compile(regexDuration);
        Matcher matcher = pattern.matcher(outInfo.toString());
        if (matcher.find()) {
            return getTime(matcher.group(1));
        }
        return 0;
    }

    /**
     * 获取时间毫秒
     * @param time 格式:"00:00:10.68"
     * @return
     */
    private static long getTime(String time) {
        int min = 0;
        String[] strs = time.split(":");
        if (strs[0].compareTo(ZERO) > 0) {
            // 秒
            min += Long.parseLong(strs[0]) * 60 * 60 * 1000;
        }
        if (strs[1].compareTo(ZERO) > 0) {
            min += Long.parseLong(strs[1]) * 60 * 1000;
        }
        if (strs[2].compareTo(ZERO) > 0) {
            min += Math.round(Double.parseDouble(strs[2]) * 1000);
        }
        return min;
    }

8、运行测试
这样设定每天2小时的课程时间,要学习哪些视频内容就很清晰了。虽然可能写这些代码的时间比手动统计的时间更长,但是方便以后,也顺便学习了ffmpeg。

当然ffmpeg的作用远不止获取时长,还可以进行视频格式的转换、视频解析等功能
在这里插入图片描述

3 其他方式

获取视频时长的方法,除了ffmpeg外还有jave,isoparser等jar包也可以实现,jave本身也是基于ffmpeg来实现的。有兴趣的小伙伴可以研究看看

源码

最后附上源码git地址,可以直接下载运行
获取视频时长demo:GetVideoTime

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wu@55555

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值