Skip to main content

WebSocket connection guide

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

Service endpoint

The WebSocket URL is fixed: wss://ap-southeast-1.maas.qwencloudapi.com/api-ws/v1/inference This example uses Singapore (ap-southeast-1). For another region, replace ap-southeast-1 in the URL, for example cn-beijing for China North 2 (Beijing), and use an API key from that region. See Regions. fun-asr-realtime-2026-02-28, fun-asr-flash-8k-realtime, and fun-asr-flash-8k-realtime-2026-01-28 are available only in China North 2 (Beijing).

Request headers

Add the following information to the request header:
ParameterTypeRequiredDescription
AuthorizationstringYesAuthentication token in the format Bearer $DASHSCOPE_API_KEY. Replace $DASHSCOPE_API_KEY with your actual API key.
user-agentstringNoClient identifier that helps the server track the request source.
X-DashScope-DataInspectionstringNoWhether to enable data compliance inspection. This parameter is omitted or set to enable by default. 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 or 403 error.

Interaction flow

For details about client events and server events, see Client events and Server-side events.
WebSocket speech recognition sequence
The client and server interact in the following order:
  1. Establish the connection: The client establishes a WebSocket connection to the server.
  2. Start the task: The client sends a run-task instruction to start the task and receives a task-started event from the server. This event confirms that the task has started and that you can proceed to the subsequent steps.
  3. Send the audio stream: The client starts sending binary audio (which must be mono) and simultaneously receives a stream of result-generated events from the server. Each event contains a speech recognition result.
  4. Notify the server to end the task: The client sends a finish-task instruction to signal the server to end the task and continues to receive result-generated events from the server.
  5. End the task: The client receives a task-finished event from the server, which indicates that the task has ended.
  6. Close the connection: The client closes the WebSocket connection.

Examples

These examples use fun-asr-realtime. Get your API key and Base URL from the console, and set them as DASHSCOPE_API_KEY and DASHSCOPE_BASE_URL. Download the sample audio as asr_example.wav: a 16 kHz, mono WAV file with 16-bit PCM encoding.
  • Java
  • Python
  • Go
  • Node.js
  • C#
  • PHP
Before you run the example, install 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("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());
    }
}
WebSocket connection guide - QwenCloud