最近项目上有个需求是获取视频的时长后返回时:分:秒的格式,在此记录一下

一、引入maven依赖

<dependencies>
	<dependency>
		<groupId>com.github.vip-zpf</groupId>
        <artifactId>jave</artifactId>
        <version>1.0.9</version>
	</dependency>
</dependencies>

二、核心代码

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;

	public String getVideoTime(MultipartFile multipartFile) throws Exception{
        //MultipartFile转File
        File file = MultipartFileToFile(multipartFile);
        if(null == file){
            throw new Exception("MultipartFile转File失败");
        }
        Encoder encoder = new Encoder();
        Long second = null;
        try (FileInputStream fis = new FileInputStream(file)){
            MultimediaInfo m = encoder.getInfo(file);

            //视频高
            int height = m.getVideo().getSize().getHeight();
            //视频宽
            int width = m.getVideo().getSize().getWidth();

            FileChannel fc = fis.getChannel();
            BigDecimal fileSize = new BigDecimal(fc.size());
            //视频大小
            String size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";

            long duration = m.getDuration() / 1000;
            second = duration;
            log.info("视频时长:{}s",duration);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return second2Time(second);
    }
 	/**
     * 将MultipartFile转换为File
     * @param multiFile 传入的文件
     * @return 出参
     */
    private File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        //时间戳+6位随机数
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String date2 = sdf2.format(new Date());
        String random = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10,5)));
        String preName = date2+random;

        try {
            File file = File.createTempFile(fileName+preName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param second 秒
     * @description: 秒转换为时分秒 HH:mm:ss 格式 仅当小时数大于0时 展示HH
     * @return: {@link String}
     */
    public static String second2Time(Long second) {
        if (second == null || second < 0) {
            return "00:00";
        }

        long h = second / 3600;
        long m = (second % 3600) / 60;
        long s = second % 60;
        String str = "";
        if (h > 0) {
            str = (h < 10 ? ("0" + h) : h) + ":";
        }
        str += (m < 10 ? ("0" + m) : m) + ":";
        str += (s < 10 ? ("0" + s) : s);
        return str;
    }

版权声明:本文为m0_46061020原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/m0_46061020/article/details/126947721