Java:获取视频文件的视频时长

发布于:2024-10-16 ⋅ 阅读:(14) ⋅ 点赞:(0)


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

3、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>