Skip to main content

WebSocket Access Guide

This topic describes the API endpoint, request headers, and interaction process for accessing the Qwen-Audio-3.1-ASR-Flash-Message real-time speech recognition service over a WebSocket connection.

API endpoint

The WebSocket API endpoint is as follows. You must use the wss:// protocol:
  • Singapore
  • China (Beijing)
  • Japan (Tokyo)
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inferenceWhen you call the API, replace {WorkspaceId} with your actual Workspace ID.
Alibaba Cloud Model Studio has launched workspace-specific domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend that you migrate 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:

Parameter

Type

Required

Description

Authorization

string

Yes

The authentication token in the format Bearer <your_api_key>. Replace <your_api_key> with your actual API Key.

user-agent

string

No

The client identifier, which helps the server track the request source.

X-DashScope-WorkSpace

string

No

The Alibaba Cloud Model Studio workspace ID.

X-DashScope-DataInspection

string

No

Specifies whether to enable data compliance checks. By default, this parameter is not passed or is set to enable. Do not enable this parameter unless necessary.

Authorization is verified during the WebSocket handshake. If the API Key is invalid or missing, the handshake fails and returns an HTTP 401/403 error.

Interaction process

For detailed descriptions of client and server events, see Client events and Server events.
WebSocket 语音识别交互时序
The interaction process between the client and the server in chronological order is as follows:
  1. Establish a connection: The client establishes a WebSocket connection with the server.
  2. Start the task: The client sends the run-task command to start the task and receives the task-started event from the server, indicating that the task has started successfully and you can proceed with the subsequent steps.
  3. Send the audio stream: The client starts to send binary audio (which must be mono) and continuously receives the result-generated events from the server. These events contain the speech recognition results.
  4. Notify the server to finish the task: The client sends the finish-task command to notify the server to finish the task and continues to receive the result-generated events from the server.
  5. Task finished: The client receives the task-finished event from the server, indicating that the task is complete.
  6. Close the connection: The client closes the WebSocket connection.

Examples

The following examples use qwen-audio-3.1-asr-flash-message. Obtain the API Key and Base URL in the console, and configure the environment variables DASHSCOPE_API_KEY and DASHSCOPE_BASE_URL respectively. Download the sample audio and save it as asr_example.wav. The audio is a WAV file encoded in 16 kHz, mono, 16-bit PCM.
  • Java
  • Python
  • Go
  • Node.js
  • C#
  • PHP
Before running the example, make sure the Java-WebSocket dependency is installed:
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-message";

    // 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("连接到服务器");
                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("任务开始");
                        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("识别结果:" + text);
                        if (payload.has("usage")) {
                            System.out.println("任务音频时长(秒):" + payload.getJSONObject("usage").get("duration"));
                        }
                        break;
                    case "task-finished":
                        System.out.println("任务完成");
                        close();
                        break;
                    case "task-failed":
                        String errMsg = message.getJSONObject("header").optString("error_message");
                        System.err.println("任务失败:" + errMsg);
                        close();
                        break;
                    default:
                        System.out.println("未知事件:" + event);
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                if (!taskStarted.get()) {
                    System.err.println("任务未启动,关闭连接");
                }
            }

            @Override
            public void onError(Exception ex) {
                System.err.println("WebSocket错误:" + 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("音频流结束");
            sendFinishTask();
        } catch (Exception e) {
            System.err.println("读取音频文件错误:" + 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());
    }
}

Available SDKs