package com.rj.audio;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SenseVoiceByXinferenceTest {
    // Xinference 集群地址（替换为你的实际地址）
    private static final String XINFERENCE_URL = "http://192.168.1.39:9997/v1/audio/speech";
    // 已部署的模型名称
    private static final String MODEL_NAME = "SenseVoiceSmall";

    public static void main(String[] args) {
        // 1. 初始化 RestTemplate
        RestTemplate restTemplate = new RestTemplate();

        // 2. 构造请求体：指定模型、输入文本
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", MODEL_NAME);
        requestBody.put("input", "这是一段测试SenseVoiceSmall模型的语音合成文本。");
        // 可选参数：调整语音风格、语速等（根据模型支持的参数添加）
        requestBody.put("voice", "default"); // 语音风格
        requestBody.put("speed", 1.0);       // 语速（1.0为正常）

        // 3. 设置请求头为 JSON 格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

        try {
            // 4. 发送 POST 请求，获取音频二进制数据
            ResponseEntity<byte[]> response = restTemplate.postForEntity(
                    XINFERENCE_URL,
                    request,
                    byte[].class
            );

            // 5. 处理响应：保存音频到本地
            if (response.getStatusCode() == HttpStatus.OK) {
                byte[] audioData = response.getBody();
                if (audioData != null) {
                    String outputPath = "sense_voice_test.wav";
                    try (FileOutputStream fos = new FileOutputStream(new File(outputPath))) {
                        fos.write(audioData);
                        System.out.println("语音合成成功，已保存到：" + outputPath);
                    }
                }
            } else {
                System.out.println("请求失败，状态码：" + response.getStatusCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}