如何使用java代码获取视频文件的时长呢?

欣喜 Java经验 发布时间:2025-01-27 11:10:19 阅读数:8991 1
下文笔者讲述java代码获取视频时长的方法分享,如下所示
使用 mp4parser.isoparser包中的相关方法
     即可获取视频时长
例:
1、导入maven依赖

<dependency>
    <groupId>org.mp4parser</groupId>
    <artifactId>isoparser</artifactId>
    <version>1.9.41</version>
</dependency>
 
2、代码案例

import com.alibaba.fastjson2.JSON;
import org.mp4parser.IsoFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

public class Test {
    public static void main(String[] args) throws ParseException {
        long spsj = readDuration(Paths.get("C:\\Users\\Administrator\\Desktop\\ceshi.mp4"));
        System.out.println(spsj);
    }

    public static long readDuration(Path mp4Path) {
        if (Files.notExists(mp4Path) || !Files.isReadable(mp4Path)) {
            System.out.println("文件路径不存在或不可读 " + mp4Path);
            return 0;
        }
        try {
            IsoFile isoFile = new IsoFile(mp4Path.toFile());
            long duration = isoFile.getMovieBox().getMovieHeaderBox().getDuration();
            long timescale = isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
            return duration / timescale;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }
}

使用注意事项

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
   在运行过程中报错:SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".

问题分析:
    org.slf4j.impl.StaticLoggerBinder通常存在于slf4j-nop.jar和slf4j-simple.jar中
	   虽然项目maven中已引入了simple包,
	   但依然存在报错
	   说明simple包未真正被加载
	   为了让包更好的加载,
	   在依赖中添加type为jar后,问题得到解决。
<!-- 依赖软件版本 -->
<properties>
    <slf4j.version>1.7.30</slf4j.version>
</properties>


<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>${slf4j.version}</version>
</dependency>
<!--         https://mvnrepository.com/artifact/org.slf4j/slf4j-simple-->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>${slf4j.version}</version>
   <!-- 注意,若无type为jar则报错-->
   <type>jar</type>
</dependency>
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202501/17379480848255.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者