package com.mortals.xhx.tts.utils;

import org.apache.commons.io.FileUtils;

import javax.sound.sampled.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.List;

/**
 * @author ZYW
 * @date 2024-08-23 9:19
 */

public class AddMp3Util {

    public static String mergeMp3s( List<String> inputFiles) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
        String outputFile = "/tmp/";
        if(System.getProperty("os.name").startsWith("Windows")){  //windows电脑测试路径
            outputFile= "F:\\\\";
        }
        File file = new File(outputFile+"new.mp3");
        if (file.exists()) {
            file.delete();
        }

        AudioFormat format = null;
        TargetDataLine targetLine = null;
        SourceDataLine sourceLine = null;

        // 获取混音所需的格式
        for (String inputFile : inputFiles) {
            ClassLoader classLoader = AddMp3Util.class.getClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream(inputFile);
            String fileName = inputFile.substring(inputFile.lastIndexOf("/")+1);
            File nowFile = new File(outputFile+fileName);
            //转换
            FileUtils.copyInputStreamToFile(inputStream, file);
            inputStream.close();
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(nowFile);
            if (format == null) {
                format = audioInputStream.getFormat();
            }
            // 处理其他文件...
        }

        // 打开目标数据行用于输出
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
        targetLine = (TargetDataLine) AudioSystem.getLine(info);
        targetLine.open(format);
        targetLine.start();

        // 打开源数据行用于输入
        info = new DataLine.Info(SourceDataLine.class, format);
        sourceLine = (SourceDataLine) AudioSystem.getLine(info);
        sourceLine.open(format);
        sourceLine.start();

        // 将源数据行连接到目标数据行
        AudioInputStream inputStream = new AudioInputStream(new SequenceInputStream(
                new FileInputStream(inputFiles.get(0)),
                new FileInputStream(inputFiles.get(1))),
                format,
                AudioSystem.NOT_SPECIFIED);

        // 将inputStream的内容复制到targetLine
        AudioSystem.write(inputStream, AudioFileFormat.Type.WAVE, new File(outputFile));

        // 关闭线路和流
        targetLine.stop();
        targetLine.close();
        sourceLine.stop();
        sourceLine.close();
        inputStream.close();

        return outputFile;
    }

}
