package com.rj.audio;

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import static java.lang.System.exit;

public class VoiceEnrollmentSampleCodes {
    public static String apiKey = System.getenv("DASHSCOPE_API_KEY");  // 如果您没有配置环境变量，请在此处用您的API-KEY进行替换
    private static String targetModel = "cosyvoice-v2";
//    private static String targetModel = "cosyvoice-v3";

    public static void main(String[] args)
            throws NoApiKeyException, InputRequiredException {
        // 复刻声音
//        VoiceEnrollmentService service = new VoiceEnrollmentService(apiKey);
//        Voice myVoice = service.createVoice(targetModel, prefix, fileUrl);
//        System.out.println("RequestId: " + service.getLastRequestId());
//        System.out.println("your voice id is " + myVoice.getVoiceId()); //cosyvoice-v3-mayun-224491d8b48344a5a483c8980eeb22fc           cosyvoice-v2-mayun-5c4ee144ead34ded8b12970101cef484
        // 使用复刻的声音来合成文本为语音
        System.out.println("开始TTS合成，使用语音: longanran");
        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(apiKey)
                .model(targetModel)
                .voice("longyingling")
                .voice("longyuan_v2")
                .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        String testText = "您好，  您可以通过以下步骤使用通义万相进行视频生成,如果您在使用过程中遇到权限问题，可以尝试在阿里云官网搜索通义万相视频生成申请体验权限";
        System.out.println("合成文本: " + testText);
        ByteBuffer audio = synthesizer.call(testText);
        // 保存合成的语音到文件
        System.out.println("TTS RequestId: " + synthesizer.getLastRequestId());
        System.out.println("音频数据大小: " + audio.array().length + " bytes");
        File file = new File("output_longyuan_v2.mp3");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(audio.array());
            System.out.println("音频文件已保存到: " + file.getAbsolutePath());
        } catch (IOException e) {
            System.err.println("保存音频文件失败: " + e.getMessage());
            throw new RuntimeException(e);
        }
        exit(0);
    }
}