Skip to main content

WebSocket access guide

This topic describes the endpoint, request headers, and interaction process for accessing the Fun-ASR-Realtime real-time speech recognition service over a WebSocket connection.

API endpoint

The WebSocket URL is fixed as follows:
  • Singapore
  • China (Beijing)
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inferenceWhen calling, replace {WorkspaceId} with your actual Workspace ID.
Alibaba Cloud Model Studio provides workspace-specific domains for the China (Beijing) and Singapore regions, delivering 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, used by the server to 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 omitted or 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 语音识别交互时序
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 instruction to start the task and receives the task-started event returned by the server, indicating that the task has started successfully and subsequent steps can proceed.
  3. Send the audio stream: the client starts sending binary audio (which must be mono audio) and simultaneously receives the result-generated events continuously returned by the server. These events contain the speech recognition results.
  4. Notify the server to finish the task: the client sends the finish-task instruction to notify the server to finish the task and continues to receive the result-generated events returned by the server.
  5. Task completion: the client receives the task-finished event returned by the server, indicating that the task has ended.
  6. Close the connection: the client closes the WebSocket connection.

Examples

The following examples use fun-asr-realtime. Obtain the API Key and Base URL in the console, and set them as 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 examples, make sure you have installed the Java-WebSocket dependency:
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 = "fun-asr-realtime";

    // 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