Skip to main content

WebSocket Integration Guide

This topic describes the interaction process, endpoint addresses, and request headers for accessing the CosyVoice real-time speech synthesis service over a WebSocket connection.

Endpoint

The WebSocket API uses the wss:// protocol, with the following addresses:
  • Singapore
  • China (Beijing)
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inferenceWhen calling, replace {WorkspaceId} with your actual Workspace ID.

Available SDKs

Alibaba Cloud Model Studio has launched workspace-dedicated domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
  • China (Beijing) region: migrate from dashscope.aliyuncs.com to {WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore region: migrate from dashscope-intl.aliyuncs.com to {WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

Request headers

Add the following information to the request headers:
ParameterTypeRequiredDescription
AuthorizationstringYesAuthentication token in the format Bearer <your_api_key>. Replace <your_api_key> with your actual API Key.
user-agentstringNoClient identifier, which helps the server track the request source.
X-DashScope-WorkSpacestringNoAlibaba Cloud Model StudioWorkspace ID。
X-DashScope-DataInspectionstringNoWhether to enable the data compliance check feature. By default, this parameter is not passed or is set to enable. Do not enable it unless necessary.
Authorization is verified during the WebSocket handshake. If the API Key is invalid or missing, the handshake fails and an HTTP 401/403 error is returned.

Interaction process

image
For detailed descriptions of client events and server events, see Client events and Server events. In chronological order, the interaction process between the client and the server is as follows:
  1. Establish the connection: The client establishes a WebSocket connection with the server.
  2. Start the task: The client sends the run-task event to start the task.
  3. Wait for confirmation: The client receives the task-started event returned by the server, indicating that the task has been successfully started and subsequent steps can proceed.
  4. Send the text to be synthesized: The client sends one or more continue-task events containing the text to be synthesized to the server in order. After receiving a complete sentence, the server returns the result-generated event and an audio stream (the text length is constrained; for details, see the description of the text field in the continue-task event).
    You can send the continue-task event multiple times to submit text segments in order. After receiving the text segments, the server automatically splits them into sentences:
    • Complete sentences are synthesized immediately, and the client receives the audio returned by the server
    • Incomplete sentences are cached until complete before synthesis; the server does not return audio while a sentence is incomplete
    When the finish-task event is sent, the server forcibly synthesizes all cached content.
  5. Receive the audio: Receive the audio stream through the binary channel
  6. Notify the server to end the task: After all text is sent, the client sends the finish-task event to notify the server to end the task, and continues to receive the audio stream returned by the server. This step must not be skipped; otherwise, the audio data may be incomplete.
  7. Task ends: The client receives the task-finished event returned by the server, indicating the end of the task.
  8. Close the connection: The client closes the WebSocket connection.
To improve resource utilization, we recommend reusing a WebSocket connection to handle multiple tasks instead of establishing a new connection for each task.
Within the same synthesis task, the run-task, all continue-task, and finish-task events must use the same task_id. Generate a new task_id each time you start a new task (for example, use a UUID). Using different task_id values will result in disordered audio or task failure.

Sample Code

The following examples use a general-purpose WebSocket library to send protocol events directly, with the cosyvoice-v3-flash model and the longanyang voice. First, obtain an API Key and configure the DASHSCOPE_API_KEY environment variable, then replace {WorkspaceId} with the workspace ID of the corresponding region; when using other regions, also replace the API address and API Key.
  • Java
  • Python
  • Go
  • C#
  • PHP
  • Node.js
We recommend using the Java DashScope SDK for development. For more information, see CosyVoice Java SDK.The following is a Java WebSocket direct connection example. Before running it, import the following dependencies:
  • Java-WebSocket
  • jackson-databind
We recommend using Maven or Gradle to manage dependencies. The configuration is as follows:
pom.xml
<dependencies>
    <!-- WebSocket Client -->
    <dependency>
        <groupId>org.java-websocket</groupId>
        <artifactId>Java-WebSocket</artifactId>
        <version>1.5.3</version>
    </dependency>

    <!-- JSON Processing -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.0</version>
    </dependency>
</dependencies>
The Java code is as follows:
import com.fasterxml.jackson.databind.ObjectMapper;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.*;

public class TTSWebSocketClient extends WebSocketClient {
    private final String taskId = UUID.randomUUID().toString();
    private final String outputFile = "output_" + System.currentTimeMillis() + ".mp3";
    private boolean taskFinished = false;

    public TTSWebSocketClient(URI serverUri, Map<String, String> headers) {
        super(serverUri, headers);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("连接成功");

        // Send the run-task event
        // If enable_ssml is set to true, only one continue-task event can be sent; otherwise the error "Text request limit violated, expected 1." will be returned
        String runTaskCommand = "{ \"header\": { \"action\": \"run-task\", \"task_id\": \"" + taskId + "\", \"streaming\": \"duplex\" }, \"payload\": { \"task_group\": \"audio\", \"task\": \"tts\", \"function\": \"SpeechSynthesizer\", \"model\": \"cosyvoice-v3-flash\", \"parameters\": { \"text_type\": \"PlainText\", \"voice\": \"longanyang\", \"format\": \"mp3\", \"sample_rate\": 22050, \"volume\": 50, \"rate\": 1, \"pitch\": 1, \"enable_ssml\": false }, \"input\": {} }}";
        send(runTaskCommand);
    }

    @Override
    public void onMessage(String message) {
        System.out.println("收到服务端返回的消息:" + message);
        try {
            // Parse JSON message
            Map<String, Object> messageMap = new ObjectMapper().readValue(message, Map.class);

            if (messageMap.containsKey("header")) {
                Map<String, Object> header = (Map<String, Object>) messageMap.get("header");

                if (header.containsKey("event")) {
                    String event = (String) header.get("event");

                    if ("task-started".equals(event)) {
                        System.out.println("收到服务端返回的task-started事件");

                        List<String> texts = Arrays.asList(
                                "床前明月光,疑是地上霜",
                                "举头望明月,低头思故乡"
                        );

                        for (String text : texts) {
                            // Send the continue-task event
                            sendContinueTask(text);
                        }

                        // Send the finish-task event
                        sendFinishTask();
                    } else if ("task-finished".equals(event)) {
                        System.out.println("收到服务端返回的task-finished事件");
                        taskFinished = true;
                        closeConnection();
                    } else if ("task-failed".equals(event)) {
                        System.out.println("任务失败:" + message);
                        closeConnection();
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("出现异常:" + e.getMessage());
        }
    }

    @Override
    public void onMessage(ByteBuffer message) {
        System.out.println("收到的二进制音频数据大小为:" + message.remaining());

        try (FileOutputStream fos = new FileOutputStream(outputFile, true)) {
            byte[] buffer = new byte[message.remaining()];
            message.get(buffer);
            fos.write(buffer);
            System.out.println("音频数据已写入本地文件" + outputFile + "中");
        } catch (IOException e) {
            System.err.println("音频数据写入本地文件失败:" + e.getMessage());
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("连接关闭:" + reason + " (" + code + ")");
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("报错:" + ex.getMessage());
        ex.printStackTrace();
    }

    private void sendContinueTask(String text) {
        String command = "{ \"header\": { \"action\": \"continue-task\", \"task_id\": \"" + taskId + "\", \"streaming\": \"duplex\" }, \"payload\": { \"input\": { \"text\": \"" + text + "\" } }}";
        send(command);
    }

    private void sendFinishTask() {
        String command = "{ \"header\": { \"action\": \"finish-task\", \"task_id\": \"" + taskId + "\", \"streaming\": \"duplex\" }, \"payload\": { \"input\": {} }}";
        send(command);
    }

    private void closeConnection() {
        if (!isClosed()) {
            close();
        }
    }

    public static void main(String[] args) {
        try {
            // The API Key differs between the Singapore and Beijing regions. Get your API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
            // If you have not configured the environment variable, replace the next line with your Model Studio API Key: String apiKey = "sk-xxx"
            String apiKey = System.getenv("DASHSCOPE_API_KEY");
            if (apiKey == null || apiKey.isEmpty()) {
                System.err.println("请设置 DASHSCOPE_API_KEY 环境变量");
                return;
            }

            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "bearer " + apiKey);
            // The following is the configuration for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.
            TTSWebSocketClient client = new TTSWebSocketClient(new URI("wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference"), headers);

            client.connect();

            while (!client.isClosed() && !client.taskFinished) {
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.err.println("连接WebSocket服务失败:" + e.getMessage());
            e.printStackTrace();
        }
    }
}