package cn.iocoder.byzs.module.ai.util.tts;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class WavHeader {
    // 添加WAV文件头
    public static byte[] addWavHeader(byte[] pcmData, int sampleRate, int bitsPerSample, int channels) {
        int byteRate = sampleRate * channels * bitsPerSample / 8;
        int blockAlign = channels * bitsPerSample / 8;
        int dataSize = pcmData.length;
        int fileSize = 44 + dataSize;

        ByteBuffer buffer = ByteBuffer.allocate(fileSize);
        buffer.order(ByteOrder.LITTLE_ENDIAN);

        // RIFF chunk
        buffer.put("RIFF".getBytes());
        buffer.putInt(fileSize - 8);
        buffer.put("WAVE".getBytes());

        // fmt subchunk
        buffer.put("fmt ".getBytes());
        buffer.putInt(16);
        buffer.putShort((short) 1);
        buffer.putShort((short) channels);
        buffer.putInt(sampleRate);
        buffer.putInt(byteRate);
        buffer.putShort((short) blockAlign);
        buffer.putShort((short) bitsPerSample);

        // data subchunk
        buffer.put("data".getBytes());
        buffer.putInt(dataSize);
        buffer.put(pcmData);

        return buffer.array();
    }
}
