package com.ruoyi.aicall.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class WavFileWriter {

    /**
     * 将Base64编码的WAV数据直接写入文件
     * @param base64String 接口返回的Base64字符串
     * @param outputPath 输出文件路径，如 "output.wav"
     */
    public static void writeWavFromBase64(String base64String, String outputPath) throws IOException {
        // Step 1: Base64解码
        byte[] wavData = Base64.getDecoder().decode(base64String);

        // Step 2: 直接写入文件（数据已包含WAV头）
        Files.write(Paths.get(outputPath), wavData);

        System.out.println("WAV文件已保存至: " + outputPath);
        System.out.println("文件大小: " + wavData.length + " bytes");

        // Step 3: 验证是否为有效WAV文件
        if (wavData.length >= 4 &&
                wavData[0] == 'R' && wavData[1] == 'I' &&
                wavData[2] == 'F' && wavData[3] == 'F') {
            System.out.println("验证通过：文件包含有效的WAV头部");
        } else {
            System.err.println("警告：未检测到WAV头部，可能是原始PCM数据");
        }
    }

    // 示例
    public static void main(String[] args) {
        try {
            String base64Data = "UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA...";
            writeWavFromBase64(base64Data, "output.wav");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
