FFmpegAudioCutterUtils.java 12.4 KB
package com.bs.reception.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhouhb
 * @CreateTime: 2024-03-12 15:18
 * @Description: ffmpeg 工具类
 */
@Slf4j
public class FFmpegAudioCutterUtils {

    /**
     * 使用FFmpeg根据时间戳切割音频文件。
     *
     * @param inputFile  需要切割的原始音频文件路径。
     * @param outputFile 切割后的音频文件输出路径。
     * @param startTime  切割开始的时间戳(单位:秒)。
     * @param endTime    切割结束的时间戳(单位:秒)。 注意:startTime和endTime都应该是浮点数,表示秒数,可以有小数部分。
     */
    public static void cutAudioByTimestamp(String inputFile, String outputFile, double startTime,
                                           double endTime) {
        try {
            // 将时间戳转换为HH:MM:SS.ms格式
            String startTimeStr = String.format("%02d:%02d:%02d.%03d", (int) (startTime / 3600),
                    (int) (startTime % 3600 / 60), (int) (startTime % 60), (int) ((startTime % 1) * 1000));
            String endTimeStr = String.format("%02d:%02d:%02d.%03d", (int) (endTime / 3600),
                    (int) (endTime % 3600 / 60), (int) (endTime % 60), (int) ((endTime % 1) * 1000));

            // 构造FFmpeg命令
            String commandprefix = ffmpegCmd();
            String[] cmdArray = new String[]{
                    commandprefix,
                    "-i", inputFile,
                    "-ss", startTimeStr,
                    "-to", endTimeStr,
                    "-c", "copy",
                    outputFile
            };
            ProcessBuilder pb = new ProcessBuilder(cmdArray);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info(line);
                }
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("音频文件按照时间戳切割成功,输出文件: " + outputFile);
            } else {
                log.info("音频文件切割失败,FFmpeg退出代码: " + exitCode);
            }
        } catch (IOException e) {
            log.error("Error executing command: " + e);
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            log.error("Error executing command: " + e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用FFmpeg工具将两个音频文件合并为一个。
     *
     * @param inputFile1 第一个输入音频文件的路径。
     * @param inputFile2 第二个输入音频文件的路径。
     * @param outputFile 合并后输出音频文件的路径。
     * @throws IOException          如果在执行命令行过程中发生IO异常。
     * @throws InterruptedException 如果在等待命令行执行过程中被中断。
     */
    public static void mergeAudio(String inputFile1, String inputFile2, String outputFile) {
        try {
            String commandprefix = ffmpegCmd();
            List<String> cmdList = new ArrayList<>();
            cmdList.add(commandprefix);
            cmdList.add("-i");
            cmdList.add(inputFile1);
            cmdList.add("-i");
            cmdList.add(inputFile2);
            cmdList.add("-filter_complex");
            cmdList.add("[0:a][1:a]concat=n=2:v=0:a=1[outa]");
            cmdList.add("-map");
            cmdList.add("[outa]");
            cmdList.add(outputFile);
            ProcessBuilder pb = new ProcessBuilder(cmdList);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info(line);
                }
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("音频文件合并成功,输出文件:" + outputFile);
            } else {
                log.info("音频文件合并失败,退出码:" + exitCode);
            }
        } catch (IOException e) {
            log.error("Error executing command: " + e);
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            log.error("Error executing command: " + e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用FFmpeg工具将多个音频文件合并为一个。
     *
     * @param list       文件的路径j集合。
     * @param outputFile 合并后输出音频文件的路径。
     * @throws IOException          如果在执行命令行过程中发生IO异常。
     * @throws InterruptedException 如果在等待命令行执行过程中被中断。
     */
    public static void mergeAudioList(List<String> list, String outputFile) {
        try {
            String commandprefix = ffmpegCmd();
            // 构建 FFmpeg 命令行参数
            List<String> cmdList = new ArrayList<>();
            cmdList.add(commandprefix);
            for (String inputFile : list) {
                cmdList.add("-i");
                cmdList.add(inputFile);
            }
            cmdList.add("-filter_complex");
            cmdList.add("concat=n=" + list.size() + ":v=0:a=1");  // 指定音频流合并,忽略视频流(假设录音文件只有音频)
            cmdList.add(outputFile);
            ProcessBuilder pb = new ProcessBuilder(cmdList);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info(line);
                }
            }
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                log.info("音频文件合并成功,输出文件:" + outputFile);
            } else {
                log.info("音频文件合并失败,退出码:" + exitCode);
            }
        } catch (IOException e) {
            log.error("Error executing command: " + e);
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            log.error("Error executing command: " + e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 计算输入音频文件的持续时间。
     * 该方法通过调用ffprobe命令行工具来获取音频文件的持续时间,并将其转换为毫秒数返回。
     *
     * @param inputFile 音频文件的路径。
     * @return 音频文件的持续时间,单位秒。如果无法获取持续时间或发生错误,则返回0。
     */
    public static long duation(String inputFile) {
        try {
            String commandprefix = ffprobeCmd();
            List<String> cmd = new ArrayList<>();
            cmd.add(commandprefix);
            cmd.add("-v");
            cmd.add("error");
            cmd.add("-show_entries");
            cmd.add("format=duration");
            cmd.add("-of");
            cmd.add("default=noprint_wrappers=1:nokey=1");
            cmd.add(inputFile);
            ProcessBuilder pb = new ProcessBuilder(cmd);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line);
                }
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                String out = output.toString().trim();
                double seconds = Double.parseDouble(out);
                return (long) Math.floor(seconds);
            } else {
                log.info("获取音频时长失败,退出码:" + exitCode);
            }
        } catch (Exception e) {
            log.error("Error reading :" + e);
            throw new RuntimeException(e);
        }
        return 0;
    }

    /**
     * 使用ffmpeg工具转换音频文件格式。
     *
     * @param inputFile  需要转换的音频文件的路径
     * @param outputFile 转换后音频文件的路径
     * @throws RuntimeException 如果执行过程中发生IO异常或线程被中断
     */
    public static void convertFormat(String inputFile, String outputFile) {
        try {
            String commandprefix = ffmpegCmd();
            // 构建 FFmpeg 命令行参数
            String[] cmdArray = new String[]{
                    commandprefix,
                    "-i", inputFile,
                    "-vn",
                    "-c:a", "libmp3lame",
                    "-qscale:a", "2",
                    outputFile
            };
            ProcessBuilder pb = new ProcessBuilder(cmdArray);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info(line);
                }
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("音频文件转化成功,输出文件:" + outputFile);
            } else {
                log.info("音频文件转化失败,退出码:" + exitCode);
            }
        } catch (Exception e) {
            log.error("Error msg :" + e);
            throw new RuntimeException(e);
        }
    }

    private static void readAndLogOutput(BufferedReader reader, String streamName) {
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                log.info(streamName + ": " + line);
            }
        } catch (Exception e) {
            log.info("Error reading " + streamName + ": " + e.getMessage());
        }
    }

    // 判断当前系统是windows还是其他
    public static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().startsWith("win");
    }

    private static String ffmpegCmd() {
        String env = System.getenv("FFMPEG_EXE");
        if (env != null && !env.isBlank()) {
            return env;
        }
        if (isWindows()) {
            return "D:\\tools\\ffmpeg\\ffmpeg-8.0.1-essentials_build\\bin\\ffmpeg.exe";
        }
        return "ffmpeg";
    }

    private static String ffprobeCmd() {
        String env = System.getenv("FFPROBE_EXE");
        if (env != null && !env.isBlank()) {
            return env;
        }
        if (isWindows()) {
            return "D:\\tools\\ffmpeg\\ffmpeg-8.0.1-essentials_build\\bin\\ffprobe.exe";
        }
        return "ffprobe";
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        // 切割音频
    /*cutAudioByTimestamp("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac",
        "F:\\360MoveData\\Users\\11\\Desktop\\test\\test20240328.aac", 3782.0,4619.0);*/
        /*convertFormat("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac","F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725aac.mp3");*/
/*
    System.out.println(duation("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac"));
*/
        // 合并音频
/*    mergeAudio("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac",
        "F:\\360MoveData\\Users\\11\\Desktop\\test\\nls-sample-16k.wav",
        "F:\\360MoveData\\Users\\11\\Desktop\\test\\hebing.acc");*/

//    List<String> list=new ArrayList<>();
//    list.add("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac");
//    list.add("F:\\360MoveData\\Users\\11\\Desktop\\test\\318402.aac");
//    mergeAudioList(list, "F:\\360MoveData\\Users\\11\\Desktop\\test\\hebing2.aac");
        System.out.println(isWindows());
    }
}