您当前的位置: 首页 >  Java

wu@55555

暂无认证

  • 0浏览

    0关注

    201博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

java: 通过ffmpeg获取视频时长

wu@55555 发布时间:2022-02-08 22:14:52 ,浏览量:0

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 details;

    /**
     * 每日任务
     */
    private SortedMap tasks;

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

4、创建返回数据包装类

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

    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 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 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 files = FileUtil.getVideoFiles(filePath, videoSuffix);
            if(files.isEmpty()){
                return R.fail(String.format("%s 该路径下未找到视频文件,请检查路径是否有误或者是否在配置文件中配置视频格式",path));
            }
            TreeMap details = new TreeMap();
            TreeMap tasks = new TreeMap();
            TreeMap 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()  {
            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 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

关注
打赏
1664985904
查看更多评论
立即登录/注册

微信扫码登录

0.0524s