package com.guwan.util;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/*
文本转语音
 */
public class SimpleAudioSaver {

    public static void main(String[] args) {
        String urlString = "http://localhost:8534/v1/audio/speech"; // API URL
        String jsonInputString = "{\"input\": \"想听个啥123\", \"voice\": \"zh-CN-XiaoxiaoNeural\", \"style\": \"\", \"rate\": 0, \"pitch\": 0}";

        saveAudio(urlString, jsonInputString);
    }

    public static void saveAudio(String urlString, String jsonInputString) {
        try {
            // 创建 URL 对象
            URL url = new URL(urlString);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式为 POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "audio/mpeg");

            // 发送请求体
            connection.getOutputStream().write(jsonInputString.getBytes("UTF-8"));

            // 处理响应
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 获取输入流
                InputStream inputStream = new BufferedInputStream(connection.getInputStream());
                // 保存文件
                try (FileOutputStream outputStream = new FileOutputStream("output.mp3")) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
                System.out.println("Audio saved as output.mp3");
            } else {
                System.err.println("Failed to get audio. Response code: " + connection.getResponseCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
