package com.heyu.api.alibaba;//  DashScope SDK 版本不低于2.21.9
// 2.20.7 及以上版本支持指定 Dylan、Jada与 Sunny 三种音色

import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class Main {
    private static final String MODEL = "qwen3-tts-flash";

    public static void call() throws ApiException, NoApiKeyException, UploadFileException {

        MultiModalConversation conv = new MultiModalConversation();

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(LLMUtils.apiKey)
                .model(MODEL)
                .text("甲、乙双方在平等自愿的基础上，就甲方委托乙方提供工商注册、代理记账、报税等本合同约定的服务，经友好协商达成如下协议，以资共同遵守。")
                .voice(AudioParameters.Voice.NOFISH)
                .languageType("Chinese") // 建议与文本语种一致，以获得正确的发音和自然的语调。
                .build();

        MultiModalConversationResult result = conv.call(param);

        String audioUrl = result.getOutput().getAudio().getUrl();

        System.out.print(audioUrl);

        // 下载音频文件到本地
        try (InputStream in = new URL(audioUrl).openStream();
             FileOutputStream out = new FileOutputStream("/Users/quyixiao/Desktop/ocr/downloaded_audio.wav")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            System.out.println("\n音频文件已下载到本地: downloaded_audio.wav");
        } catch (Exception e) {
            System.out.println("\n下载音频文件时出错: " + e.getMessage());
        }
    }
    public static void main(String[] args) {
        try {
            call();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}