Skip to main content

Guia de conexão por WebSocket

Acesse o service de síntese de fala em tempo real Qwen-Audio-TTS por meio de uma conexão WebSocket. Este tópico aborda os endpoints do service, os cabeçalhos de requisição e o fluxo de interação entre cliente e servidor. O SDK do DashScope oferece suporte apenas a Java e Python. Para outras linguagens, utilize uma conexão WebSocket. Limites de taxa: As chamadas aos modelos estão sujeitas a limites de taxa. Quando um limite é excedido, o servidor retorna o erro Requests rate limit exceeded, please try again later. Reduza a taxa de requisições ou a concorrência e tente novamente. Para consultar os limites de taxa de cada modelo, consulte Rate limiting.

Endpoints do service

URL WebSocket fixa:
  • Singapore
  • China (Beijing)
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inferenceSubstitua {WorkspaceId} pelo seu workspace ID real.
O Alibaba Cloud Model Studio lançou domínios específicos por workspace para as regiões China (Beijing) e Singapore. Os novos domínios dedicados oferecem desempenho superior e maior estabilidade para requisições de inferência. Recomendamos a migração para os novos domínios:
  • China (Beijing): de dashscope.aliyuncs.com para {WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore: de dashscope-intl.aliyuncs.com para {WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

Cabeçalhos de requisição

Inclua os seguintes cabeçalhos na requisição:
ParâmetroTipoObrigatórioDescrição
AuthorizationstringSimFormato: Bearer <API key>. Substitua <API key> pela sua chave de API.
user-agentstringNãoIdentificador do cliente para rastreamento de requisições.
X-DashScope-WorkSpacestringNãoworkspace ID do Alibaba Cloud Model Studio.
X-DashScope-DataInspectionstringNãoAtive a inspeção de dados. Padrão: enable. Deixe sem definição, a menos que seja necessário.
A autorização é verificada durante o handshake WebSocket. Se a chave de API for inválida ou estiver ausente, o handshake falhará com um erro HTTP 401/403.

Fluxo de interação

image
Para obter detalhes sobre eventos do lado do cliente e do servidor, consulte Eventos do cliente e Eventos do servidor. Sequência de interação entre cliente e servidor:
  1. Estabeleça a conexão: Crie uma conexão WebSocket com o servidor.
  2. Inicie uma tarefa: Envie um evento run-task.
  3. Aguarde a confirmação: Receba um evento task-started do servidor antes de prosseguir.
  4. Envie o texto para síntese: Envie um ou mais eventos continue-task contendo o texto a ser sintetizado, em sequência. O servidor retorna um evento result-generated com um fluxo de áudio após cada frase completa. Para verificar os limites de tamanho do texto, consulte o campo text no evento continue-task.
    Envie vários eventos continue-task com segmentos de texto em ordem. O servidor divide o texto em frases:
    • Frases completas são sintetizadas e retornadas como áudio imediatamente.
    • Frases incompletas ficam em buffer até serem concluídas.
    Um evento finish-task força a síntese de todo o conteúdo armazenado em buffer.
  5. Receba o áudio: Leia o fluxo de áudio do canal binary.
  6. Encerre a tarefa: Após enviar todo o texto, envie um evento finish-task e continue recebendo o áudio. Esta etapa é obrigatória — ignorá-la pode resultar em áudio incompleto.
  7. Receba a conclusão da tarefa: Um evento task-finished enviado pelo servidor confirma que a tarefa foi concluída.
  8. Feche a conexão: Desconecte o WebSocket.
Reutilize a conexão WebSocket entre tarefas em vez de criar uma nova para cada uma delas.
Todos os eventos em uma tarefa de síntese (run-task, continue-task, finish-task) devem compartilhar o mesmo task_id. Gere um novo task_id (como um UUID) para cada tarefa. Valores incompatíveis causam corrupção de áudio ou falha na tarefa.

Exemplos de código

Estes exemplos usam bibliotecas WebSocket genéricas para enviar eventos diretamente, com qwen-audio-3.1-tts-flash e a voz longanhuan_v3.1. Obtenha uma chave de API, defina DASHSCOPE_API_KEY e substitua {WorkspaceId} pelo ID do workspace da região. Ao trocar de região, altere o endpoint e a chave de API.
  • Java
  • Python
  • Go
  • C#
  • PHP
  • Node.js
Recomendamos usar o DashScope SDK para Java. Consulte Qwen-Audio-TTS Java SDK.O exemplo a seguir usa WebSocket diretamente em Java. Importe estas dependências antes de executar:
  • Java-WebSocket
  • jackson-databind
Use Maven ou Gradle para gerenciar as dependências:
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>
Código Java:
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("Connection established");

        // 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\": \"qwen-audio-3.1-tts-flash\", \"parameters\": { \"text_type\": \"PlainText\", \"voice\": \"longanhuan_v3.1\", \"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("Received message from server: " + 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("Received task-started event from server");

                        List<String> texts = Arrays.asList(
                                "Before my bed, moonlight shines bright,I suspect it\'s frost upon the ground.",
                                "I raise my eyes to gaze at the bright moon,then bow my head, thinking of home."
                        );

                        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("Received task-finished event from server");
                        taskFinished = true;
                        closeConnection();
                    } else if ("task-failed".equals(event)) {
                        System.out.println("Task failed: " + message);
                        closeConnection();
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("Exception occurred: " + e.getMessage());
        }
    }

    @Override
    public void onMessage(ByteBuffer message) {
        System.out.println("Received binary audio data of size: " + message.remaining());

        try (FileOutputStream fos = new FileOutputStream(outputFile, true)) {
            byte[] buffer = new byte[message.remaining()];
            message.get(buffer);
            fos.write(buffer);
            System.out.println("Audio data written to local file " + outputFile);
        } catch (IOException e) {
            System.err.println("Failed to write audio data to local file: " + e.getMessage());
        }
    }

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

    @Override
    public void onError(Exception ex) {
        System.err.println("Error: " + 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("Please set the DASHSCOPE_API_KEY environment variable");
                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("Failed to connect to WebSocket service: " + e.getMessage());
            e.printStackTrace();
        }
    }
}