Tous les produits
Search
Centre de documentation

Alibaba Cloud Model Studio:CosyVoice Java SDK

Dernière mise à jour :Nov 27, 2026

Prérequis

接口地址

SDK的接口地址需在初始化前设置为下方地址(包含WorkspaceId)。如需切换到其他地域,请修改 Constants.baseWebsocketApiUrl为对应地域的URL。

新加坡

wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference

调用时请将{WorkspaceId}替换为真实的Workspace ID。

华北2(北京)

wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference

调用时请将{WorkspaceId}替换为真实的Workspace ID。

Important阿里云百炼为华北2(北京)、新加坡地域推出了业务空间专属域名,能够为推理请求提供卓越的性能和更高的稳定性,建议迁移至新域名:

  • 华北2(北京)地域:从 dashscope.aliyuncs.com 迁移至 {WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • 新加坡地域:从 dashscope-intl.aliyuncs.com 迁移至 {WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

Démarrage rapide

Cet exemple utilise la région Singapour. Remplacez {WorkspaceId} dans le code par votre identifiant d'espace de travail. L'exemple enregistre l'audio sous le nom output.mp3 dans le répertoire courant.

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.utils.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class Main {
    // 模型
    private static String model = "cosyvoice-v3-plus";
    // 音色
    private static String voice = "longanyang";

    public static void streamAudioDataToSpeaker() {
        // 请求参数
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(model) // 模型
                        .voice(voice) // 音色
                        .build();

        // 同步模式:禁用回调(第二个参数为null)
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        ByteBuffer audio = null;
        try {
            // 阻塞直至音频返回
            audio = synthesizer.call("今天天气怎么样?");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 任务结束关闭websocket连接
            synthesizer.getDuplexApi().close(1000, "bye");
        }
        if (audio != null) {
            // 将音频数据保存到本地文件"output.mp3"中
            File file = new File("output.mp3");
            // 首次发送文本时需建立 WebSocket 连接,因此首包延迟会包含连接建立的耗时
            System.out.println(
                    "[Metric] requestId为:"
                            + synthesizer.getLastRequestId()
                            + "首包延迟(毫秒)为:"
                            + synthesizer.getFirstPackageDelay());
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(audio.array());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        // 以下为新加坡地域的配置,调用时请将"{WorkspaceId}"替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        streamAudioDataToSpeaker();
        System.exit(0);
    }
}

Qwen-Audio-TTS / CosyVoice

L'exemple suivant utilise Qwen-Audio-TTS. Pour appeler CosyVoice, remplacez model par cosyvoice-v3-plus et voice par longanyang.

Le SDK fournit les interfaces clés pour la synthèse vocale et prend en charge les méthodes d'appel suivantes :

  • Appel non streaming : bloquant. Le texte intégral est envoyé en une seule fois et l'audio complet est renvoyé directement. Adapté aux scénarios de synthèse vocale de textes courts.
  • Appel streaming unidirectionnel : non bloquant. Le texte intégral est envoyé en une seule fois et les données audio (éventuellement par blocs) sont reçues via une fonction de rappel. Adapté aux scénarios de synthèse vocale de textes courts exigeant des performances élevées en temps réel.
  • Appel streaming bidirectionnel : non bloquant. Les fragments de texte peuvent être envoyés en plusieurs lots et les flux audio synthétisés de manière incrémentielle sont reçus en temps réel via une fonction de rappel. Adapté aux scénarios de synthèse vocale de textes longs exigeant des performances élevées en temps réel.

Appel non streaming

image

发送的文本长度不得超过20000字符。

Important每次调用call方法前,需要重新初始化SpeechSynthesizer实例。

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.utils.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class Main {
    // 模型
    private static String model = "qwen-audio-3.0-tts-flash";
    // 音色
    private static String voice = "longanhuan_v3.6";

    public static void streamAudioDataToSpeaker() {
        // 请求参数
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // 新加坡地域和北京地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                        // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(model) // 模型
                        .voice(voice) // 音色
                        .build();

        // 同步模式:禁用回调(第二个参数为null)
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        ByteBuffer audio = null;
        try {
            // 阻塞直至音频返回
            audio = synthesizer.call("今天天气怎么样?");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 任务结束关闭websocket连接
            synthesizer.getDuplexApi().close(1000, "bye");
        }
        if (audio != null) {
            // 将音频数据保存到本地文件"output.mp3"中
            File file = new File("output.mp3");
            // 首次发送文本时需建立 WebSocket 连接,因此首包延迟会包含连接建立的耗时
            System.out.println(
                    "[Metric] requestId为:"
                            + synthesizer.getLastRequestId()
                            + "首包延迟(毫秒)为:"
                            + synthesizer.getFirstPackageDelay());
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(audio.array());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        // 以下为新加坡地域的配置,调用时请将"{WorkspaceId}"替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        streamAudioDataToSpeaker();
        System.exit(0);
    }
}

Appel streaming unidirectionnel

image

发送的文本长度不得超过20000字符。

Important每次调用call方法前,需要重新初始化SpeechSynthesizer实例。

import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.utils.Constants;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;

class TimeUtils {
    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    public static String getTimestamp() {
        return LocalDateTime.now().format(formatter);
    }
}

public class Main {
    // 模型
    private static String model = "qwen-audio-3.0-tts-flash";
    // 音色
    private static String voice = "longanhuan_v3.6";

    public static void streamAudioDataToSpeaker() {
        CountDownLatch latch = new CountDownLatch(1);

        // 实现回调接口ResultCallback
        ResultCallback<SpeechSynthesisResult> callback = new ResultCallback<SpeechSynthesisResult>() {
            @Override
            public void onEvent(SpeechSynthesisResult result) {
                if (result.getAudioFrame() != null) {
                    // 此处实现保存音频数据到本地的逻辑
                    System.out.println(TimeUtils.getTimestamp() + " 收到音频");
                }
                // 获取输出信息,包含事件类型和原始文本
                if (result.getOutput() != null && result.getOutput().has("type")) {
                    System.out.println("事件类型: " + result.getOutput().get("type").getAsString()
                            + ", 原始文本: " + (result.getOutput().has("original_text") ? result.getOutput().get("original_text").getAsString() : ""));
                }
            }

            @Override
            public void onComplete() {
                System.out.println(TimeUtils.getTimestamp() + " 收到Complete,语音合成结束");
                latch.countDown();
            }

            @Override
            public void onError(Exception e) {
                System.out.println("出现异常:" + e.toString());
                latch.countDown();
            }
        };

        // 请求参数
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // 新加坡地域和北京地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                        // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(model) // 模型
                        .voice(voice) // 音色
                        .build();
        // 第二个参数"callback"传入回调即启用异步模式
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, callback);
        // 非阻塞调用,立即返回null(实际结果通过回调接口异步传递),在回调接口的onEvent方法中实时获取二进制音频
        try {
            synthesizer.call("今天天气怎么样?");
            // 等待合成完成
            latch.await();
            // 等待播放线程全部播放完
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 任务结束后关闭websocket连接
            synthesizer.getDuplexApi().close(1000, "bye");
        }
        // 首次发送文本时需建立 WebSocket 连接,因此首包延迟会包含连接建立的耗时
        System.out.println(
                "[Metric] requestId为:"
                        + synthesizer.getLastRequestId()
                        + ",首包延迟(毫秒)为:"
                        + synthesizer.getFirstPackageDelay());
    }

    public static void main(String[] args) {
        // 以下为新加坡地域的配置,调用时请将"{WorkspaceId}"替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        streamAudioDataToSpeaker();
        System.exit(0);
    }
}

Appel streaming bidirectionnel

image

单次发送文本长度不得超过 20000 字符,且累计发送文本总长度不得超过 20 万字符。

  • 流式输入时可多次调用streamingCall按顺序提交文本片段。服务端接收文本片段后自动进行分句:

    • 完整语句立即合成
    • 不完整语句缓存至完整后合成

    调用 streamingComplete 时,服务端会强制合成所有已接收但未处理的文本片段(包括未完成的句子)。

  • 发送文本片段的间隔不得超过23秒,否则触发“request timeout after 23 seconds”异常。

    若无待发送文本,需及时调用 streamingComplete结束任务。

    Important请务必确保调用streamingComplete方法,否则可能会导致结尾部分的文本无法成功转换为语音。

    服务端强制设定23秒超时机制,客户端无法修改该配置。

import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisAudioFormat;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.utils.Constants;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class TimeUtils {
    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    public static String getTimestamp() {
        return LocalDateTime.now().format(formatter);
    }
}

public class Main {
    private static String[] textArray = {"流式文本语音合成SDK,",
            "可以将输入的文本", "合成为语音二进制数据,", "相比于非流式语音合成,",
            "流式合成的优势在于实时性", "更强。用户在输入文本的同时",
            "可以听到接近同步的语音输出,", "极大地提升了交互体验,",
            "减少了用户等待时间。", "适用于调用大规模", "语言模型(LLM),以",
            "流式输入文本的方式", "进行语音合成的场景。"};
    private static String model = "qwen-audio-3.0-tts-flash"; // 模型
    private static String voice = "longanhuan_v3.6"; // 音色

    public static void streamAudioDataToSpeaker() {
        // 配置回调函数
        ResultCallback<SpeechSynthesisResult> callback = new ResultCallback<SpeechSynthesisResult>() {
            @Override
            public void onEvent(SpeechSynthesisResult result) {
                // System.out.println("收到消息: " + result);
                if (result.getAudioFrame() != null) {
                    // 此处实现处理音频数据的逻辑
                    System.out.println(TimeUtils.getTimestamp() + " 收到音频");
                }
            }

            @Override
            public void onComplete() {
                System.out.println(TimeUtils.getTimestamp() + " 收到Complete,语音合成结束");
            }

            @Override
            public void onError(Exception e) {
                System.out.println("出现异常:" + e.toString());
            }
        };

        // 请求参数
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // 新加坡地域和北京地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                        // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(model)
                        .voice(voice)
                        .format(SpeechSynthesisAudioFormat
                                .PCM_22050HZ_MONO_16BIT) // 流式合成使用PCM或者MP3
                        .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, callback);
        // 带Callback的call方法将不会阻塞当前线程
        try {
            for (String text : textArray) {
                // 发送文本片段,在回调接口的onEvent方法中实时获取二进制音频
                synthesizer.streamingCall(text);
            }
            // 等待结束流式语音合成
            synthesizer.streamingComplete();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 任务结束关闭websocket连接
            synthesizer.getDuplexApi().close(1000, "bye");
        }

        // 首次发送文本时需建立 WebSocket 连接,因此首包延迟会包含连接建立的耗时
        System.out.println(
                "[Metric] requestId为:"
                        + synthesizer.getLastRequestId()
                        + ",首包延迟(毫秒)为:"
                        + synthesizer.getFirstPackageDelay());
    }

    public static void main(String[] args) {
        // 以下为新加坡地域的配置,调用时请将"{WorkspaceId}"替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        streamAudioDataToSpeaker();
        System.exit(0);
    }
}

通过Flowable调用

Flowable是RxJava中表示响应式数据流的类型,支持背压。关于Flowable的使用,请参见Flowable API详情。

使用Flowable前需确保已集成RxJava库,并了解响应式编程基础概念。

单次发送文本长度不得超过 20000 字符,且累计发送文本总长度不得超过 20 万字符。

单向流式调用

以下示例展示了通过Flowable对象的blockingForEach接口,阻塞式地获取每次流式返回的SpeechSynthesisResult类型数据。

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class TimeUtils {
    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    public static String getTimestamp() {
        return LocalDateTime.now().format(formatter);
    }
}

public class Main {
    private static String model = "qwen-audio-3.0-tts-flash"; // 模型
    private static String voice = "longanhuan_v3.6"; // 音色

    public static void streamAudioDataToSpeaker() throws NoApiKeyException {
        // 请求参数
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // 新加坡地域和北京地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                        // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(model) // 模型
                        .voice(voice) // 音色
                        .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        synthesizer.callAsFlowable("今天天气怎么样?").blockingForEach(result -> {
            if (result.getAudioFrame() != null) {
                // 此处实现处理音频数据的逻辑
                System.out.println(TimeUtils.getTimestamp() + " 收到音频");
            }
            // 获取输出信息,包含事件类型和原始文本
            if (result.getOutput() != null && result.getOutput().has("type")) {
                System.out.println("事件类型: " + result.getOutput().get("type").getAsString()
                        + ", 原始文本: " + (result.getOutput().has("original_text") ? result.getOutput().get("original_text").getAsString() : ""));
            }
        });
        // 任务结束关闭 WebSocket 连接
        synthesizer.getDuplexApi().close(1000, "bye");
        // 首次发送文本时需建立 WebSocket 连接,因此首包延迟会包含连接建立的耗时
        System.out.println(
                "[Metric] requestId为:"
                        + synthesizer.getLastRequestId()
                        + "首包延迟(毫秒)为:"
                        + synthesizer.getFirstPackageDelay());
    }

    public static void main(String[] args) throws NoApiKeyException {
        // 以下为新加坡地域的配置,调用时请将"{WorkspaceId}"替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        streamAudioDataToSpeaker();
        System.exit(0);
    }
}

双向流式调用

以下示例展示了通过Flowable对象作为输入参数,输入文本流。并通过Flowable对象作为返回值,利用的blockingForEach接口,阻塞式地获取每次流式返回的SpeechSynthesisResult类型数据。

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class TimeUtils {
    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    public static String getTimestamp() {
        return LocalDateTime.now().format(formatter);
    }
}

public class Main {
    private static String[] textArray = {"流式文本语音合成SDK,",
            "可以将输入的文本", "合成为语音二进制数据,", "相比于非流式语音合成,",
            "流式合成的优势在于实时性", "更强。用户在输入文本的同时",
            "可以听到接近同步的语音输出,", "极大地提升了交互体验,",
            "减少了用户等待时间。", "适用于调用大规模", "语言模型(LLM),以",
            "流式输入文本的方式", "进行语音合成的场景。"};
    private static String model = "qwen-audio-3.0-tts-flash";
    private static String voice = "longanhuan_v3.6";

    public static void streamAudioDataToSpeaker() throws NoApiKeyException {
        // 模拟流式输入
        Flowable<String> textSource = Flowable.create(emitter -> {
            new Thread(() -> {
                for (int i = 0; i < textArray.length; i++) {
                    emitter.onNext(textArray[i]);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                emitter.onComplete();
            }).start();
        }, BackpressureStrategy.BUFFER);

        // 请求参数
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // 新加坡地域和北京地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                        // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(model) // 模型
                        .voice(voice) // 音色
                        .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        synthesizer.streamingCallAsFlowable(textSource).blockingForEach(result -> {
            if (result.getAudioFrame() != null) {
                // 此处实现播放音频的逻辑
                System.out.println(
                        TimeUtils.getTimestamp() +
                                " 二进制音频大小为:" + result.getAudioFrame().capacity());
            }
            // 获取输出信息,包含事件类型和原始文本
            if (result.getOutput() != null && result.getOutput().has("type")) {
                System.out.println("事件类型: " + result.getOutput().get("type").getAsString()
                        + ", 原始文本: " + (result.getOutput().has("original_text") ? result.getOutput().get("original_text").getAsString() : ""));
            }
        });
        synthesizer.getDuplexApi().close(1000, "bye");
        // 首次发送文本时需建立 WebSocket 连接,因此首包延迟会包含连接建立的耗时
        System.out.println(
                "[Metric] requestId为:"
                        + synthesizer.getLastRequestId()
                        + ",首包延迟(毫秒)为:"
                        + synthesizer.getFirstPackageDelay());
    }

    public static void main(String[] args) throws NoApiKeyException {
        // 以下为新加坡地域的配置,调用时请将"{WorkspaceId}"替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        streamAudioDataToSpeaker();
        System.exit(0);
    }
}

高并发调用

在DashScope Java SDK中,采用了OkHttp3的连接池技术,以减少重复建立连接的开销。详情请参见高并发最佳实践。

Paramètres de la requête

CosyVoice

SpeechSynthesisParam

Chemin du package: com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam

Exemple:

SpeechSynthesisParam param = SpeechSynthesisParam.builder()
    .model("cosyvoice-v3-plus") // 模型
    .voice("longanyang") // 音色
    .format(SpeechSynthesisAudioFormat.WAV_8000HZ_MONO_16BIT) // 音频编码格式、采样率
    .volume(50) // 音量,取值范围:[0, 100]
    .speechRate(1.0f) // 语速,取值范围:[0.5, 2]
    .pitchRate(1.0f) // 语调,取值范围:[0.5, 2]
    .build();
Méthodes du builder
MéthodeType de paramètreObligatoireDescription
model(String)StringOuiNom du modèle.
voice(String)StringOuiLa voix utilisée pour la synthèse vocale.
  • Voix système : voir Liste des voix CosyVoice
  • Voix clonées : personnalisées via la fonctionnalité de clonage de voix
  • Voix conçues : personnalisées via la fonctionnalité de création de voix
format(SpeechSynthesisAudioFormat)enumNonFormat d'encodage audio et fréquence d'échantillonnage.

Valeur par défaut : SpeechSynthesisAudioFormat.MP3_22050HZ_MONO_256KBPS.

Chemin du package de SpeechSynthesisAudioFormat : com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisAudioFormat.

volume(int)intNonVolume.

Valeur par défaut : 50.

Plage valide : [0, 100].

speechRate(float)floatNonVitesse de parole.

Valeur par défaut : 1.0.

Plage valide : [0.5, 2.0].

pitchRate(float)floatNonTon.

Valeur par défaut : 1.0.

Plage valide : [0.5, 2.0].

enableWordTimestamp(boolean)booleanNonIndique s'il faut activer les horodatages au niveau des mots.

Valeur par défaut : false.

Disponible uniquement en mode de sortie en streaming. Voix prises en charge : voix clonées des modèles cosyvoice-v3.5-plus, cosyvoice-v3.5-flash, cosyvoice-v3-flash, cosyvoice-v3-plus et cosyvoice-v2, ainsi que les voix système marquées comme prises en charge dans la liste des voix CosyVoice. Les voix clonées d'autres modèles ne prennent pas en charge cette fonctionnalité.

seed(int)intNonGraine aléatoire utilisée lors de la génération, qui fait varier les résultats de synthèse. Lorsque la version du modèle, le texte, la voix et d'autres paramètres sont identiques, l'utilisation de la même graine reproduit le même résultat de synthèse.

Valeur par défaut : 0.

Plage valide : [0, 65535].

Pour les versions du SDK antérieures à 2.21.7, seed doit être défini via les paramètres d'extension.

languageHints(List<String>)List<String>Non

Important

  • Ce paramètre est un tableau, mais la version actuelle ne traite que le premier élément ; nous vous recommandons donc de ne transmettre qu'une seule valeur.
  • Ce paramètre spécifie la langue cible de la synthèse vocale. Ce paramétrage est indépendant de la langue de l'échantillon audio utilisé pour le clonage de voix. Pour définir la langue source d'une tâche de clonage, consultezRéférence de l'API de clonage de voix。

Spécifiez la langue cible de la synthèse vocale pour améliorer la qualité de la synthèse.

Utilisez ce paramètre lorsque la lecture des nombres, abréviations ou symboles, ou la qualité de la synthèse pour les langues moins courantes, ne répond pas aux attentes. Par exemple :

  • La lecture des nombres ne répond pas aux attentes : « hello, this is 110 » est lu « hello, this is one one zero » au lieu de « hello, this is yao yao ling »
  • Lecture inexacte des symboles : « @ » est lu « ai te » au lieu de « at »
  • Qualité de synthèse médiocre pour les langues moins courantes ; la voix synthétisée sonne de manière artificielle

Plage de valeurs

  • zh : chinois
  • en : anglais
  • fr : français
  • de : allemand
  • ja : japonais
  • ko : coréen
  • ru : russe
  • pt : portugais
  • th : thaï
  • id : indonésien
  • vi : vietnamien
  • es : espagnol
  • it : italien
  • ms : malais
  • fil : filipino
  • ar : arabe
instruction(String)StringNonDéfinissez des instructions pour contrôler les effets de synthèse tels que le dialecte, l'émotion ou le rôle.

Pour connaître les instructions d'utilisation, consultez Contrôle par instruction.

parameter(String key, Object value)String, ObjectNonDéfinit des paramètres étendus.
parameters(Map<String, Object>)MapNonDéfinit des paramètres étendus.
Paramètres étendus

Défini via parameter() ou parameters().

Exemple:

SpeechSynthesisParam param = SpeechSynthesisParam.builder()
  .model("cosyvoice-v3-plus")
  .voice("longanyang")
  .parameter("bit_rate", 32)
  .build();
Nom du paramètreTypeRequisDescription
bit_rateintegerNonDébit audio (kbps). Lorsque le format audio est mp3 ou opus, le débit peut être ajusté via le paramètre bit_rate.

Valeur par défaut : 32.

Plage de valeurs : [6, 510].

enable_aigc_tagbooleanNonIndique s'il faut ajouter un filigrane implicite AIGC à l'audio généré. Lorsque ce paramètre est défini sur true, le filigrane implicite est intégré dans l'audio aux formats pris en charge (wav/mp3/opus).

Valeur par défaut : false.

RemarqueSeuls cosyvoice-v3-flash, cosyvoice-v3-plus et cosyvoice-v2 prennent en charge cette fonctionnalité.

aigc_propagatorStringNonDéfinit le champ ContentPropagator du filigrane implicite AIGC, utilisé pour identifier le propagateur du contenu. N'est effectif que lorsque enable_aigc_tag est true.

Valeur par défaut : UID Alibaba Cloud.

RemarqueSeuls cosyvoice-v3-flash, cosyvoice-v3-plus et cosyvoice-v2 prennent en charge cette fonctionnalité.

aigc_propagate_idStringNonDéfinit le champ PropagateID du filigrane implicite AIGC, utilisé pour identifier de manière unique une action de propagation spécifique. N'est effectif que lorsque enable_aigc_tag est true.

Valeur par défaut : le Request ID de cette requête de synthèse vocale.

RemarqueSeuls cosyvoice-v3-flash, cosyvoice-v3-plus et cosyvoice-v2 prennent en charge cette fonctionnalité.

enable_markdown_filterbooleanNon

Remarquecosyvoice-v2 ne prend pas en charge cette fonctionnalité.

Indique s'il faut activer le filtrage Markdown. Une fois activé, le service convertit le Markdown en texte adapté à la lecture à voix haute avant la synthèse.

Valeur par défaut : false.

Valeurs valides :

  • true : activer le filtrage Markdown
  • false : désactiver le filtrage Markdown

Référence API

构造方法

public SpeechSynthesizer(SpeechSynthesisParam param, ResultCallback<SpeechSynthesisResult> callback)

参数说明:

  • param:语音合成参数,通过SpeechSynthesisParam .builder()构建
  • callback:回调函数,用于流式调用。非流式调用时传入null

call() - 非流式/单向流式合成

方法签名:

public ByteBuffer call(String text)

参数说明:

参数类型必填说明
textString是待合成的文本,长度不得超过20000字符。

返回值:ByteBuffer 或 null。非流式调用时返回完整音频数据;单向流式调用时音频通过回调返回,此方法返回null。

streamingCall() - 双向流式合成

方法签名:

public void streamingCall(String text)

参数说明:

参数类型必填说明
textString是待合成的文本,长度不得超过20000字符。可多次调用追加文本。

streamingComplete() - 结束双向流式调用

方法签名:

public void streamingComplete()

结束双向流式调用,通知服务端所有文本已发送完毕。

callAsFlowable() - 单向流式合成(响应式)

方法签名:

public Flowable<SpeechSynthesisResult> callAsFlowable(String text)

参数说明:

参数类型必填说明
textString是待合成的文本。

返回值:Flowable< SpeechSynthesisResult > 响应式流。

streamingCallAsFlowable() - 双向流式合成(响应式)

方法签名:

public Flowable<SpeechSynthesisResult> streamingCallAsFlowable(Flowable<String> textStream)

参数说明:

参数类型必填说明
textStreamFlowable<String>是文本的响应式流。

返回值:Flowable< SpeechSynthesisResult > 响应式流。

getDuplexApi().close() - 关闭WebSocket连接

方法签名:

public boolean getDuplexApi().close(int code, String reason)

参数说明:

参数类型必填说明
codeint是关闭码。
reasonString是关闭原因。

返回值:boolean,是否成功关闭。

getLastRequestId() - 获取请求ID

方法签名:

public String getLastRequestId()

返回值:String,请求ID。

getFirstPackageDelay() - 获取首包延迟

方法签名:

public long getFirstPackageDelay()

返回值:long,首包延迟(ms),从发送第一包到收到首包结果。

onEvent() - 接收音频数据

方法签名:

public void onEvent(SpeechSynthesisResult result)

参数说明:

参数类型必填说明
resultSpeechSynthesisResult是接收到合成事件时触发,包含音频帧、时间戳信息和输出信息(事件类型、原始文本等)。

onComplete() - 合成完成

方法签名:

public void onComplete()

语音合成完成时触发。

onError() - 错误处理

方法签名:

public void onError(Exception e)

参数说明:

参数类型必填说明
eException是发生错误时触发,包含异常信息。

getAudioFrame() - 获取音频数据帧

方法签名:

public ByteBuffer getAudioFrame()

返回值:ByteBuffer,音频数据帧。

getTimestamp() - 获取时间戳信息

方法签名:

public Sentence getTimestamp()

返回值:Sentence,时间戳信息。

getOutput() - 获取输出信息

方法签名:

public JsonObject getOutput()

Valeur de retour : com.google.gson.JsonObject, les informations de sortie de l'événement de synthèse, contenant le type d'événement et le contenu textuel. Nécessite une version du SDK >= 2.22.0.

getBeginTime() - 获取句子开始时间

方法签名:

public int getBeginTime()

返回值:句子开始时间,单位为ms。

getEndTime() - 获取句子结束时间

方法签名:

public int getEndTime()

返回值:句子结束时间,单位为ms。

getWords() - 获取字级别时间戳

方法签名:

public List<Word> getWords()

Valeur de retour : une collection List d'objets Word, qui contient les informations d'horodatage par lot au niveau du mot et peut être vide.

getBeginTime() - 获取词开始时间

方法签名:

public int getBeginTime()

返回值:词开始时间,单位为ms。

getEndTime() - 获取词结束时间

方法签名:

public int getEndTime()

返回值:词结束时间,单位为ms。

getText() - 获取文本信息

方法签名:

public String getText()

返回值:String,文本信息。

getPhonemes() - 获取音素级别时间戳

方法签名:

public List<Phoneme> getPhonemes()

Valeur de retour : une collection List d'objets Phoneme, qui contient les informations d'horodatage par lot au niveau du phonème et peut être vide.

getBeginTime() - 获取音素开始时间

方法签名:

public int getBeginTime()

返回值:音素开始时间,单位为ms。

getEndTime() - 获取音素结束时间

方法签名:

public int getEndTime()

返回值:音素结束时间,单位为ms。

getText() - 获取文本信息

方法签名:

public String getText()

返回值:String,文本信息。

getTone() - 获取音调

方法签名:

public int getTone()

返回值:音调。

  • 英文中,0、1、2分别代表轻音、重音和次重音。
  • 拼音中,1、2、3、4、5分别代表一声、二声、三声、四声和轻声。

Informations de sortie (output)

getOutput()返回JsonObject,封装了合成事件的输出信息。在onEvent回调或Flowable流中获取。包含以下字段:

字段类型说明
typeString事件类型。取值:sentence-begin(句子开始,返回待合成的文本内容)、sentence-synthesis(标识音频数据块,表示当前正在合成音频)、sentence-end(句子结束,返回文本内容和字级别时间戳)。
original_textString当前句子的原始文本内容。在sentence-begin和sentence-end事件中返回。
sentenceJsonObject句子信息,包含句子编号(index)和字级别时间戳(words)。在sentence-end事件中包含完整的字级别时间戳信息。

CosyVoice

SpeechSynthesizer

Chemin du package : com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer

streamingCancel() - Annuler l'appel de streaming bidirectionnel

Signature de la méthode :

public void streamingCancel()

Description : annule la tâche de synthèse vocale en streaming bidirectionnel du tour en cours. Après l'appel, le SDK met immédiatement fin à la tâche en cours. Après l'annulation, vous pouvez démarrer une nouvelle tâche de synthèse sur la connexion actuelle sans réinitialiser l'instance SpeechSynthesizer.

ImportantExigence de version : Cette fonctionnalité nécessite le SDK Java 2.22.26 ou une version ultérieure.

ImportantLimitations du modèle :

  • Chine (Pékin) : Les modèles CosyVoice nécessitent la version v2 ou ultérieure.
  • Singapour : Les modèles CosyVoice ne prennent pas en charge cette fonctionnalité.

ResultCallback

Package : com.alibaba.dashscope.common.ResultCallback

SpeechSynthesisResult

Package : com.alibaba.dashscope.audio.tts.SpeechSynthesisResult

Informations d'horodatage au niveau de la phrase (Sentence)

Sentence encapsule les informations d'horodatage au niveau de la phrase.

Informations d'horodatage au niveau du mot (Word)

Word encapsule les informations d'horodatage au niveau du mot.

Informations d'horodatage au niveau du phonème (Phoneme)

Phoneme encapsule les informations d'horodatage au niveau du phonème.