Skip to main content

Guia de conexão por WebSocket

Este tópico descreve o endpoint de service, os cabeçalhos de requisição e o fluxo de interação para acessar o service de reconhecimento de fala em tempo real Qwen-Audio-ASR-Streaming por meio de uma conexão WebSocket.

Endpoint do service

A 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 da requisição

Adicione as seguintes informações ao cabeçalho da requisição:
ParâmetroTipoObrigatórioDescrição
AuthorizationstringSimToken de autenticação no formato Bearer <your_api_key>. Substitua <your_api_key> pela sua chave de API real.
user-agentstringNãoIdentificador do cliente que ajuda o servidor a rastrear a source da requisição.
X-DashScope-WorkSpacestringNãoworkspace ID do Model Studio.
X-DashScope-DataInspectionstringNãoIndica se a inspeção de conformidade de dados deve ser ativada. Este parâmetro é omitido ou definido como enable por padrão. Não ative este parâmetro 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á e retornará um erro HTTP 401 ou 403.

Fluxo de interação

Para obter detalhes sobre eventos do cliente e do servidor, consulte Client events e Server-side events.
WebSocket speech recognition sequence
O cliente e o servidor interagem na seguinte ordem:
  1. Estabeleça a conexão: O cliente estabelece uma conexão WebSocket com o servidor.
  2. Inicie a tarefa: O cliente envia uma instrução run-task para iniciar a tarefa e recebe um evento task-started do servidor. Esse evento confirma que a tarefa foi iniciada e que você pode prosseguir para as etapas subsequentes.
  3. Envie o fluxo de áudio: O cliente começa a enviar áudio binário (que deve ser mono) e recebe simultaneamente um fluxo de eventos result-generated do servidor. Cada evento contém um resultado de reconhecimento de fala.
  4. Notifique o servidor para encerrar a tarefa: O cliente envia uma instrução finish-task para sinalizar ao servidor o fim da tarefa e continua recebendo eventos result-generated do servidor.
  5. Encerre a tarefa: O cliente recebe um evento task-finished do servidor, indicando que a tarefa terminou.
  6. Feche a conexão: O cliente fecha a conexão WebSocket.

Exemplos de chamada

Os exemplos usam qwen-audio-3.1-asr-flash-streaming. Obtenha a chave de API e a Base URL no console e defina DASHSCOPE_API_KEY e DASHSCOPE_BASE_URL. Baixe o áudio de exemplo como asr_example.wav: um arquivo WAV mono de 16 kHz com codificação PCM de 16 bits.
  • Java
  • Python
  • Go
  • Node.js
  • C#
  • PHP
Antes de executar o exemplo, instale a dependência Java-WebSocket:
Maven
<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.5.6</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20240303</version>
</dependency>
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;

import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

public class FunASRRealtimeClient {

    private static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");
    private static final String URL = "wss://" + URI.create(System.getenv("DASHSCOPE_BASE_URL")).getHost() + "/api-ws/v1/inference";
    private static final String AUDIO_FILE = "asr_example.wav"; // Replace with the path to your audio file
    private static final String MODEL = "qwen-audio-3.1-asr-flash-streaming";

    // Generate a 32-character random ID
    private static final String TASK_ID = UUID.randomUUID().toString().replace("-", "").substring(0, 32);

    private static final AtomicBoolean taskStarted = new AtomicBoolean(false);
    private static WebSocketClient client;

    public static void main(String[] args) throws Exception {
        client = new WebSocketClient(new URI(URL)) {
            @Override
            public void onOpen(ServerHandshake handshake) {
                System.out.println("Connected to server");
                sendRunTask();
            }

            @Override
            public void onMessage(String data) {
                JSONObject message = new JSONObject(data);
                String event = message.getJSONObject("header").getString("event");
                switch (event) {
                    case "task-started":
                        System.out.println("Task started");
                        taskStarted.set(true);
                        new Thread(FunASRRealtimeClient::sendAudioStream).start();
                        break;
                    case "result-generated":
                        JSONObject payload = message.getJSONObject("payload");
                        String text = payload.getJSONObject("output").getJSONObject("sentence").getString("text");
                        System.out.println("Recognition result: " + text);
                        if (payload.has("usage")) {
                            System.out.println("Audio duration (seconds): " + payload.getJSONObject("usage").get("duration"));
                        }
                        break;
                    case "task-finished":
                        System.out.println("Task finished");
                        close();
                        break;
                    case "task-failed":
                        String errMsg = message.getJSONObject("header").optString("error_message");
                        System.err.println("Task failed: " + errMsg);
                        close();
                        break;
                    default:
                        System.out.println("Unknown event: " + event);
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                if (!taskStarted.get()) {
                    System.err.println("Task not started, closing connection");
                }
            }

            @Override
            public void onError(Exception ex) {
                System.err.println("WebSocket error: " + ex.getMessage());
            }
        };
        client.addHeader("Authorization", "bearer " + API_KEY);
        client.connectBlocking();
    }

    // Send the run-task instruction
    private static void sendRunTask() {
        JSONObject runTask = new JSONObject()
                .put("header", new JSONObject()
                        .put("action", "run-task")
                        .put("task_id", TASK_ID)
                        .put("streaming", "duplex"))
                .put("payload", new JSONObject()
                        .put("task_group", "audio")
                        .put("task", "asr")
                        .put("function", "recognition")
                        .put("model", MODEL)
                        .put("parameters", new JSONObject()
                                .put("sample_rate", 16000)
                                .put("format", "wav"))
                        .put("input", new JSONObject()));
        client.send(runTask.toString());
    }

    // Send the audio stream (send one binary chunk every 100ms)
    private static void sendAudioStream() {
        int chunkSize = 3200; // 100ms @ 16kHz 16bit mono
        try {
            byte[] audio = Files.readAllBytes(Paths.get(AUDIO_FILE));
            int offset = 0;
            while (offset < audio.length) {
                int end = Math.min(offset + chunkSize, audio.length);
                byte[] chunk = new byte[end - offset];
                System.arraycopy(audio, offset, chunk, 0, end - offset);
                client.send(ByteBuffer.wrap(chunk));
                offset = end;
                Thread.sleep(100);
            }
            System.out.println("Audio stream ended");
            sendFinishTask();
        } catch (Exception e) {
            System.err.println("Error reading audio file: " + e.getMessage());
            client.close();
        }
    }

    // Send the finish-task instruction
    private static void sendFinishTask() {
        JSONObject finishTask = new JSONObject()
                .put("header", new JSONObject()
                        .put("action", "finish-task")
                        .put("task_id", TASK_ID)
                        .put("streaming", "duplex"))
                .put("payload", new JSONObject()
                        .put("input", new JSONObject()));
        client.send(finishTask.toString());
    }
}