package com.fuyuanshen.global.mqtt.utils;

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

public class FfmpegVolumeUtil3 {

    /**
     * 使用FFmpeg增加MP3文件的音量
     *
     * @param inputFilePath  输入MP3文件路径
     * @param outputFilePath 输出MP3文件路径
     * @param volumeGain     音量增益（例如：1.5表示增加50%音量，2.0表示翻倍）
     */
    public static void increaseMp3Volume(String inputFilePath, String outputFilePath, int volumeGain) {
        boolean ffmpegAvailable = isFfmpegAvailable();
        if (!ffmpegAvailable) {
            System.err.println("FFmpeg未安装或未找到！请安装FFmpeg并确保在系统路径中。");
            return;
        }
        // 创建输出文件的父目录
        File outputFile = new File(outputFilePath);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            boolean created = parentDir.mkdirs();
            if (!created) {
                System.err.println("无法创建输出目录：" + parentDir.getAbsolutePath());
                return;
            }
        }
        Process process = null;
        try {
            // 构建FFmpeg命令
            String command = String.format(
                    "ffmpeg -y -i \"%s\" -af \"volume=%sdB\" \"%s\"",
                    inputFilePath,
                    volumeGain,
                    outputFilePath
            );

            System.out.println("执行命令: " + command);

            // 执行FFmpeg命令
            process = Runtime.getRuntime().exec(command);

            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待命令执行完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("音量调整成功！输出文件：" + outputFilePath);
            } else {
                System.err.println("FFmpeg命令执行失败，退出码：" + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

    public static void main(String[] args) {

        // 示例用法
        String inputPath = "/app/input.mp3";
        String outputPath = "/app/output18.mp3";
        int volumeGain = 12;

        increaseMp3Volume(inputPath, outputPath, volumeGain);
    }

    private static boolean isFfmpegAvailable() {
        try {
            Process process = Runtime.getRuntime().exec("ffmpeg -version");
            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (Exception e) {
            return false;
        }
    }

}

