package shop.alien.util.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class VideoDurationFFmpeg {
    //获取视频文件时长
    public static long getVideoDuration(String filePath) throws IOException, InterruptedException {
        // 构建 FFmpeg 命令
        String[] command = {
                "ffprobe",
                "-v", "error",
                "-show_entries", "format=duration",
                "-of", "default=noprint_wrappers=1:nokey=1",
                filePath
        };
        // 创建进程构建器
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        // 启动进程
        Process process = processBuilder.start();
        // 读取进程输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        long duration = 0;
        while ((line = reader.readLine()) != null) {
            try {
                // 将输出转换为毫秒
                duration = (long) (Double.parseDouble(line) * 1000);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        // 等待进程结束
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            // 若执行失败，读取错误信息
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder errorMessage = new StringBuilder();
            String errorLine;
            while ((errorLine = errorReader.readLine()) != null) {
                errorMessage.append(errorLine).append("\n");
            }
            throw new IOException("FFmpeg 命令执行失败，退出码: " + exitCode + ", 错误信息: " + errorMessage.toString());
        }
        return duration;
    }

    public static String getFileNameFromUrl(String url) {
        int lastIndex = url.lastIndexOf('/');
        if (lastIndex != -1) {
            return url.substring(lastIndex + 1);
        }
        return "";
    }

    public static void main(String[] args) {
        String filePath = "D:/2497682.mp4";
        try {
            long duration = getVideoDuration(filePath);
            System.out.println("视频时长: " + duration + " 毫秒");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}