Skip to main content

WebSocket access guide

The Qwen-ASR-Realtime real-time speech recognition service uses the WebSocket protocol to receive real-time audio streams and transcribe them in real time. It supports the VAD mode and Manual mode interaction processes.

User guide: For model introduction and selection recommendations, see Speech recognition; for sample code, see Real-time speech recognition.

API endpoint

The WebSocket URL is fixed as follows. The model to call is specified via the model query parameter (replace <model_name> with the actual model):
  • Singapore
  • China (Beijing)
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime?model=<model_name>When calling, replace {WorkspaceId} with your actual Workspace ID.
Alibaba Cloud Model Studio provides workspace-dedicated domains for the China (Beijing) and Singapore regions, delivering superior performance and higher stability for inference requests. Migrating to the new domains is recommended:
  • 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
Replace {WorkspaceId} with your actual Workspace ID. The existing domains still work.
The URL must use the wss:// protocol. Authorization is set in the request header (see Request headers), and the model is specified via the model URL query parameter.

Request headers

Add the following information to the request header:

Parameter

Type

Required

Description

Authorization

string

Yes

Authentication token, in the format Bearer <your_api_key>; replace <your_api_key> with your actual API Key.

user-agent

string

No

Client identifier that helps the server track the request source.

X-DashScope-WorkSpace

string

No

The Alibaba Cloud Model Studio workspace ID.

X-DashScope-DataInspection

string

No

Whether to enable the data compliance check feature. By default, it is not passed or is set to enable. Do not enable it unless necessary.

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

Interaction process

For details about client and server events, see Client events and Server events. Two interaction modes are supported:
  • VAD mode (default): The server automatically detects the start and end of speech (utterance segmentation), making it suitable for scenarios such as real-time conversations and meeting transcription.
  • Manual mode: The client controls utterance segmentation, suitable for scenarios where the client can clearly determine utterance boundaries, such as sending voice messages in chat apps.
The model does not return sentence-level or word-level timestamps for the transcribed text. The speech start and end times in VAD events describe speech activity boundaries; see the corresponding events for field descriptions.

VAD mode (default)

The server default value of silence_duration_ms is 800; for scenarios that require fast utterance segmentation, such as conversations and chat, 400 can be used as a reference. The server default value of threshold is 0.2. For the complete configuration, see Client events. The server automatically detects the start and end of speech (utterance segmentation). The developer only needs to continuously send the audio stream, and the server automatically returns the final recognition result when it detects that an utterance has ended. This mode is suitable for scenarios such as real-time conversations and meeting transcription. To enable: Configure the session.turn_detection parameter of the client session.update event.
image
  • The client appends audio to the buffer by sending the input_audio_buffer.append event.
  • The server returns the input_audio_buffer.speech_started event when it detects speech. Note: If the client has not received this event yet and sends session.finish directly to end the session, the server returns the session.finished event directly, after which the client must disconnect on its own.
  • The client continues to send input_audio_buffer.append events to submit audio.
  • After all audio has been submitted, the client sends a session.finish event to notify the server to end the current session.
    In VAD mode, after all audio has been sent, you must send the session.finish event before closing the connection. If the client closes the WebSocket connection directly without sending this event, the server discards the current in_progress item, and events such as conversation.item.input_audio_transcription.completed will not arrive. We recommend sending {"type":"session.finish"} before calling ws.Close(), and closing the connection only after receiving the session.finished event.
  • The server returns the input_audio_buffer.speech_stopped event when it detects the end of speech.
  • The server returns the input_audio_buffer.committed event.
  • The server returns the conversation.item.created event.
  • The server returns the conversation.item.input_audio_transcription.text event, which contains real-time speech recognition results.
  • The server returns the conversation.item.input_audio_transcription.completed event, which contains the final speech recognition result.
  • The server returns the session.finished event to notify the client that recognition is complete; at this point, the client must disconnect on its own.

Manual mode

The client controls utterance segmentation. The client needs to send the audio of a complete utterance and then send an input_audio_buffer.commit event to notify the server. This mode is suitable for scenarios where the client can clearly determine utterance boundaries, such as sending voice messages in chat apps. To enable: Set session.turn_detection of the client session.update event to null.
image
  • The client appends audio to the buffer by sending the input_audio_buffer.append event.
  • The client submits the input audio buffer by sending the input_audio_buffer.commit event. The commit creates a new user message item in the conversation.
  • The client sends a session.finish event to notify the server to end the current session.
  • The server returns the input_audio_buffer.committed event in response.
  • The server returns the conversation.item.input_audio_transcription.text event, which contains real-time speech recognition results.
  • The server returns the conversation.item.input_audio_transcription.completed event, which contains the final speech recognition result.
  • The server returns the session.finished event to notify the client that recognition is complete; at this point, the client must disconnect on its own.

Examples

The following examples use qwen3-asr-flash-realtime. Get an API Key and Base URL in the console, and configure 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.
The sample code reads asr_example.pcm (PCM16, 16 kHz, mono). If you only have files in formats such as MP3/WAV, use ffmpeg to convert them:
ffmpeg -i asr_example.wav -ar 16000 -ac 1 -f s16le asr_example.pcm
When using the non-VAD (Manual) mode, we recommend that the cumulative duration of audio sent in a single session does not exceed 60 seconds.
  • Java
  • Python
  • Go
  • Node.js
  • C#
  • PHP
Before running the example, 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.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.*;

public class QwenASRRealtimeClient {

    private static final Logger logger = Logger.getLogger(QwenASRRealtimeClient.class.getName());
    private static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");
    private static final String MODEL = "qwen3-asr-flash-realtime";

    // Controls whether to use VAD mode
    private static final boolean enableServerVad = true;

    private static final AtomicBoolean isRunning = new AtomicBoolean(true);
    private static WebSocketClient client;

    public static void main(String[] args) throws Exception {
        initLogger();

        String baseUrl = "wss://" + URI.create(System.getenv("DASHSCOPE_BASE_URL")).getHost() + "/api-ws/v1/realtime";
        String url = baseUrl + "?model=" + MODEL;
        logger.info("Connecting to server: " + url);

        client = new WebSocketClient(new URI(url)) {
            @Override
            public void onOpen(ServerHandshake handshake) {
                logger.info("Connected to server.");
                sendSessionUpdate();
            }

            @Override
            public void onMessage(String message) {
                try {
                    JSONObject data = new JSONObject(message);
                    String eventType = data.optString("type");

                    logger.info("Received event: " + data.toString(2));

                    // The final recognition result is in the transcription.completed event
                    if ("conversation.item.input_audio_transcription.completed".equals(eventType)) {
                        logger.info("Final transcript: " + data.optString("transcript"));
                    }

                    // On receiving the finished event -> stop the sending thread and close the connection
                    if ("session.finished".equals(eventType)) {
                        logger.info("Closing WebSocket connection after session finished...");

                        isRunning.set(false); // Stop the audio sending thread
                        if (this.isOpen()) {
                            this.close(1000, "ASR finished");
                        }
                    }
                } catch (Exception e) {
                    logger.severe("Failed to parse message: " + message);
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                logger.info("Connection closed: " + code + " - " + reason);
            }

            @Override
            public void onError(Exception ex) {
                logger.severe("Error: " + ex.getMessage());
            }
        };

        // Add request headers
        client.addHeader("Authorization", "Bearer " + API_KEY);
        client.addHeader("OpenAI-Beta", "realtime=v1");

        client.connectBlocking(); // Block until the connection is established

        // Replace with the path to the audio file to be recognized
        String localAudioPath = "asr_example.pcm";
        Thread audioThread = new Thread(() -> {
            try {
                sendAudio(localAudioPath);
            } catch (Exception e) {
                logger.severe("Audio sending thread error: " + e.getMessage());
            }
        });
        audioThread.start();
    }

    /** Session update event (enable/disable VAD) */
    private static void sendSessionUpdate() {
        JSONObject eventNoVad = new JSONObject()
                .put("event_id", "event_123")
                .put("type", "session.update")
                .put("session", new JSONObject()
                        .put("modalities", new String[]{"text"})
                        .put("input_audio_format", "pcm")
                        .put("sample_rate", 16000)
                        // .put("input_audio_transcription", new JSONObject()
                        //         .put("language", "zh"))
                        .put("turn_detection", JSONObject.NULL) // Manual mode
                );

        JSONObject eventVad = new JSONObject()
                .put("event_id", "event_123")
                .put("type", "session.update")
                .put("session", new JSONObject()
                        .put("modalities", new String[]{"text"})
                        .put("input_audio_format", "pcm")
                        .put("sample_rate", 16000)
                        // .put("input_audio_transcription", new JSONObject()
                        //         .put("language", "zh"))
                        .put("turn_detection", new JSONObject()
                                .put("type", "server_vad")
                                .put("threshold", 0.2)
                                .put("silence_duration_ms", 400))
                );

        if (enableServerVad) {
            logger.info("Sending event (VAD):\n" + eventVad.toString(2));
            client.send(eventVad.toString());
        } else {
            logger.info("Sending event (Manual):\n" + eventNoVad.toString(2));
            client.send(eventNoVad.toString());
        }
    }

    /** Send the audio file stream */
    private static void sendAudio(String localAudioPath) throws Exception {
        Thread.sleep(3000); // Wait for the session to be ready
        byte[] allBytes = Files.readAllBytes(Paths.get(localAudioPath));
        logger.info("文件读取开始");

        int offset = 0;
        while (isRunning.get() && offset < allBytes.length) {
            int chunkSize = Math.min(3200, allBytes.length - offset);
            byte[] chunk = new byte[chunkSize];
            System.arraycopy(allBytes, offset, chunk, 0, chunkSize);
            offset += chunkSize;

            if (client != null && client.isOpen()) {
                String encoded = Base64.getEncoder().encodeToString(chunk);
                JSONObject eventd = new JSONObject()
                        .put("event_id", "event_" + System.currentTimeMillis())
                        .put("type", "input_audio_buffer.append")
                        .put("audio", encoded);

                client.send(eventd.toString());
                logger.info("Sending audio event: " + eventd.getString("event_id"));
            } else {
                break; // Avoid continuing to send after disconnection
            }

            Thread.sleep(100); // Simulate real-time sending
        }

        logger.info("文件读取完毕");

        if (client != null && client.isOpen()) {
            // Non-VAD mode requires commit
            if (!enableServerVad) {
                JSONObject commitEvent = new JSONObject()
                        .put("event_id", "event_789")
                        .put("type", "input_audio_buffer.commit");
                client.send(commitEvent.toString());
                logger.info("Sent commit event for manual mode.");
            }

            JSONObject finishEvent = new JSONObject()
                    .put("event_id", "event_987")
                    .put("type", "session.finish");
            client.send(finishEvent.toString());
            logger.info("Sent finish event.");
        }
    }

    /** Initialize logging */
    private static void initLogger() {
        logger.setLevel(Level.ALL);
        Logger rootLogger = Logger.getLogger("");
        for (Handler h : rootLogger.getHandlers()) {
            rootLogger.removeHandler(h);
        }

        Handler consoleHandler = new ConsoleHandler();
        consoleHandler.setLevel(Level.ALL);
        consoleHandler.setFormatter(new SimpleFormatter());
        logger.addHandler(consoleHandler);
    }
}

Available SDKs