package com.vetti.common.ai.whisper;

import javax.sound.sampled.*;
import java.io.*;

public class AudioToPCM {
    public static void main(String[] args) {
        File inputFile = new File("/Users/wangxiangshun/Desktop/临时文件/110/3f7d2f6b-ea3d-4134-9abf-e8d8d30f91b7.wav");  // 输入音频文件
        File outputFile = new File("/Users/wangxiangshun/Desktop/临时文件/110/output_pcm_audio1.pcm");  // 输出PCM格式文件
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputFile);
            // 进行后续操作，如播放等
        } catch (UnsupportedAudioFileException e) {
            System.out.println("Unsupported audio file format: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Error reading the file: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
        try {
            // 读取音频文件
            AudioInputStream inputAudioStream = AudioSystem.getAudioInputStream(inputFile);

            // 获取音频文件的格式信息
            AudioFormat sourceFormat = inputAudioStream.getFormat();
            System.out.println("Input Audio Format: " + sourceFormat);

            // 设置目标PCM格式 (可以是16-bit, 8kHz, Mono, Linear PCM)
            AudioFormat pcmFormat = new AudioFormat(
                    AudioFormat.Encoding.PCM_SIGNED,
                    sourceFormat.getSampleRate(),
                    16,  // 16-bit samples
                    1,    // 单声道
                    2,    // 每个样本2字节（16位）
                    sourceFormat.getSampleRate(),
                    false // 大端模式
            );

            // 获取PCM格式的音频流
            AudioInputStream pcmAudioStream = AudioSystem.getAudioInputStream(pcmFormat, inputAudioStream);

            // 创建输出文件流
            FileOutputStream fos = new FileOutputStream(outputFile);
            byte[] buffer = new byte[1024];
            int bytesRead;

            // 将PCM音频数据写入输出文件
            while ((bytesRead = pcmAudioStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            // 关闭流
            pcmAudioStream.close();
            fos.close();

            System.out.println("Audio has been converted to PCM format and saved at: " + outputFile.getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

