Skip to main content

Qwen-TTS-Realtime Java SDK

This document describes the key interfaces and request parameters for calling Qwen-TTS-Realtime models with the DashScope Java SDK.

Prerequisites

The DashScope Java SDK version must be 2.22.7 or later.

QuickStart

import com.alibaba.dashscope.audio.qwen_tts_realtime.*;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.google.gson.JsonObject;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.AudioSystem;
import java.io.*;
import java.util.Base64;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    static String[] textToSynthesize = {
            "对吧~我就特别喜欢这种超市",
            "尤其是过年的时候",
            "去逛超市",
            "就会觉得",
            "超级超级开心!",
            "想买好多好多的东西呢!"
    };
    public static QwenTtsRealtimeAudioFormat ttsFormat = QwenTtsRealtimeAudioFormat.PCM_24000HZ_MONO_16BIT;

    // Real-time PCM audio player
    public static class RealtimePcmPlayer {
        private int sampleRate;
        private SourceDataLine line;
        private AudioFormat audioFormat;
        private Thread decoderThread;
        private Thread playerThread;
        private AtomicBoolean stopped = new AtomicBoolean(false);
        private Queue<String> b64AudioBuffer = new ConcurrentLinkedQueue<>();
        private Queue<byte[]> RawAudioBuffer = new ConcurrentLinkedQueue<>();
        private ByteArrayOutputStream totalAudioStream = new ByteArrayOutputStream();

        // Initialize the audio format and audio line.
        public RealtimePcmPlayer(int sampleRate) throws LineUnavailableException {
            this.sampleRate = sampleRate;
            this.audioFormat = new AudioFormat(this.sampleRate, 16, 1, true, false);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
            line = (SourceDataLine) AudioSystem.getLine(info);
            line.open(audioFormat);
            line.start();
            decoderThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!stopped.get()) {
                        String b64Audio = b64AudioBuffer.poll();
                        if (b64Audio != null) {
                            byte[] rawAudio = Base64.getDecoder().decode(b64Audio);
                            RawAudioBuffer.add(rawAudio);
                            // Write audio data to totalAudioStream.
                            try {
                                totalAudioStream.write(rawAudio);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            });
            playerThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!stopped.get()) {
                        byte[] rawAudio = RawAudioBuffer.poll();
                        if (rawAudio != null) {
                            try {
                                playChunk(rawAudio);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            });
            decoderThread.start();
            playerThread.start();
        }

        // Play an audio chunk and block until playback completes.
        private void playChunk(byte[] chunk) throws IOException, InterruptedException {
            if (chunk == null || chunk.length == 0) return;

            int bytesWritten = 0;
            while (bytesWritten < chunk.length) {
                bytesWritten += line.write(chunk, bytesWritten, chunk.length - bytesWritten);
            }
            int audioLength = chunk.length / (this.sampleRate*2/1000);
            // Wait for the buffered audio to finish playing.
            Thread.sleep(audioLength - 10);
        }

        public void write(String b64Audio) {
            b64AudioBuffer.add(b64Audio);
        }

        public void cancel() {
            b64AudioBuffer.clear();
            RawAudioBuffer.clear();
        }

        public void waitForComplete() throws InterruptedException {
            while (!b64AudioBuffer.isEmpty() || !RawAudioBuffer.isEmpty()) {
                Thread.sleep(100);
            }
            line.drain();
        }

        public void shutdown() throws InterruptedException, IOException {
            stopped.set(true);
            decoderThread.join();
            playerThread.join();

            // Save the complete audio file.
            File file = new File("TotalAudio_"+ttsFormat.getSampleRate()+"."+ttsFormat.getFormat());
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(totalAudioStream.toByteArray());
            }

            if (line != null && line.isRunning()) {
                line.drain();
                line.close();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException, LineUnavailableException, IOException {
        QwenTtsRealtimeParam param = QwenTtsRealtimeParam.builder()
                .model("qwen3-tts-flash-realtime")
                // The following is the configuration for the Singapore region.
                .url("wss://dashscope-intl.aliyuncs.com/api-ws/v1/realtime")
                // The API Key differs between the Singapore and Beijing regions. Get your API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
                .apikey(System.getenv("DASHSCOPE_API_KEY"))
                .build();
        AtomicReference<CountDownLatch> completeLatch = new AtomicReference<>(new CountDownLatch(1));
        final AtomicReference<QwenTtsRealtime> qwenTtsRef = new AtomicReference<>(null);

        // Create a real-time audio player instance.
        RealtimePcmPlayer audioPlayer = new RealtimePcmPlayer(24000);

        QwenTtsRealtime qwenTtsRealtime = new QwenTtsRealtime(param, new QwenTtsRealtimeCallback() {
            @Override
            public void onOpen() {
                // Handle connection establishment.
            }
            @Override
            public void onEvent(JsonObject message) {
                String type = message.get("type").getAsString();
                switch(type) {
                    case "session.created":
                        // Handle session creation.
                        if (message.has("session")) {
                            String eventId = message.get("event_id").getAsString();
                            String sessionId = message.get("session").getAsJsonObject().get("id").getAsString();
                            System.out.println("[onEvent] session.created, session_id: "
                                    + sessionId + ", event_id: " + eventId);
                        }
                        break;
                    case "response.audio.delta":
                        String recvAudioB64 = message.get("delta").getAsString();
                        // Play audio in real time.
                        audioPlayer.write(recvAudioB64);
                        break;
                    case "response.done":
                        // Handle response completion.
                        break;
                    case "session.finished":
                        // Handle session termination.
                        completeLatch.get().countDown();
                    default:
                        break;
                }
            }
            @Override
            public void onClose(int code, String reason) {
                // Handle connection closure.
            }
        });
        qwenTtsRef.set(qwenTtsRealtime);
        try {
            qwenTtsRealtime.connect();
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        }
        QwenTtsRealtimeConfig config = QwenTtsRealtimeConfig.builder()
                .voice("Cherry")
                .responseFormat(ttsFormat)
                .mode("server_commit")
                .build();
        qwenTtsRealtime.updateSession(config);
        for (String text:textToSynthesize) {
            qwenTtsRealtime.appendText(text);
            Thread.sleep(100);
        }
        qwenTtsRealtime.finish();
        completeLatch.get().await();
        qwenTtsRealtime.close();

        // Wait for audio playback to complete, then shut down the player.
        audioPlayer.waitForComplete();
        audioPlayer.shutdown();
        System.exit(0);
    }
}
Visit github to download more sample code.

Request parameters

The following request parameters can be configured through the chained methods or setters of the QwenTtsRealtimeParam object, and then passed as a parameter to the constructor of QwenTtsRealtime to complete the configuration.

Parameter

Type

Required

Description

model

String

Yes

Model name. Seesupported models。

url

String

Yes

China (Beijing) region: wss://dashscope.aliyuncs.com/api-ws/v1/realtime

Singapore region: wss://dashscope-intl.aliyuncs.com/api-ws/v1/realtime

The following request parameters can be configured through the chained methods or setters of the QwenTtsRealtimeConfig object, and then passed as a parameter to the updateSession API to complete the configuration.

Parameter

Type

Required

Description

voice

String

Yes

The voice used for speech synthesis. SeeQwen-TTS voice list。

languageType

String

No

The language of the synthesized audio. The default is Auto.

  • Auto: Suitable for scenarios where the language of the text cannot be determined or the text contains multiple languages. The model automatically matches the corresponding pronunciation for each language fragment in the text, but fully accurate pronunciation cannot be guaranteed.

  • Specified language: Suitable for scenarios where the text is in a single language. In this case, specifying a concrete language can significantly improve synthesis quality, usually delivering better results than Auto. Valid values include:

    • Chinese

    • English

    • German

    • Italian

    • Portuguese

    • Spanish

    • Japanese

    • Korean

    • French

    • Russian

mode

String

No

Interaction mode. Valid values:

  • server_commit (default): The server automatically determines when to start synthesis, balancing latency and quality. Recommended for most scenarios

  • commit: The client manually triggers synthesis, with the lowest latency, but you must manage sentence integrity on your own

format

String

No

The format of the audio output by the model.

Supported formats:

  • pcm (default)

  • wav

  • mp3

  • opus

sampleRate

int

No

The sample rate (Hz) of the audio output by the model.

Supported sample rates:

  • 8000

  • 16000

  • 24000 (default)

  • 48000

speechRate

float

No

The speech rate of the audio. 1.0 is the normal rate, less than 1.0 is slower, and greater than 1.0 is faster.

Default value: 1.0.

Value range: [0.5, 2.0].

volume

int

No

The volume of the audio.

Value range: [0, 100].

pitchRate

float

No

The pitch of the synthesized audio.

Default value: 1.0.

Value range: [0.5, 2.0].

bitRate

int

No

Specifies the audio'sbit rate(kbps). A higher bit rate delivers better audio quality but a larger audio file. This parameter is available only when the audio format (response_format) is opus.

Default value: 128.

Value range: [6, 510].

API reference

QwenTtsRealtime class

Import method:
import com.alibaba.dashscope.audio.qwen_tts_realtime.QwenTtsRealtime;
Member methodsMethod signatureServer response events (delivered via callbacks)Description
connect
public void connect() throws NoApiKeyException, InterruptedException
session.created
The session has been created
session.updated
The session configuration has been updated
Creates a connection to the server.
updateSession
public void updateSession(QwenTtsRealtimeConfig config)
session.updated
The session configuration has been updated
Updates the default configuration for interactions in this session. For parameter configuration, see the "Request parameters" section.After you establish a connection, the server promptly returns the default input and output configuration for this session. If you need to update the default session configuration, we recommend that you always call this API immediately after establishing the connection.After receiving the session.update event, the server validates the parameters. If any parameter is invalid, an error is returned; otherwise, the server-side session configuration is updated.
appendText
public void appendText(String text)
NoneAppends a text fragment to the cloud-side input text buffer. The buffer is a temporary store that you can write to and commit later.
  • In "server_commit" mode, the server decides when to commit and synthesize the text in the text buffer.
  • In "commit" mode, the client must actively trigger speech synthesis via commit.
clearAppendedText
public void clearAppendedText()
input_text_buffer.cleared
Clear the text received on the server
Deletes the text in the current cloud buffer.
commit
public void commit()
input_text_buffer.committed
Submit text and trigger speech synthesis
response.output_item.added
New output content in the response
response.content_part.added
New output content added to the assistant message item
response.audio.deltaAudio incrementally generated by the modelresponse.audio.doneAudio generation completedresponse.content_part.doneThe audio content of the assistant message has finished streaming outputresponse.output_item.doneAll output items of the assistant message have finished streamingresponse.doneResponse completed
Submits the text previously appended to the cloud buffer via append, and immediately synthesizes all the text. If the input text buffer is empty, an error will occur.
  • In "server_commit" mode, the client does not need to send this event; the server commits the text buffer automatically.
  • In "commit" mode, the client must trigger speech synthesis via commit.
finish
public void finish()
session.finishedResponse completedTerminates the task.
close
public void close()
NoneCloses the connection.
getSessionId
public String getSessionId()
NoneObtains the session_id of the current task.
getResponseId
public String getResponseId()
NoneObtains the response_id of the most recent response.
getFirstAudioDelay
public long getFirstAudioDelay()
NoneObtains the first audio packet latency.

Callback interface (QwenTtsRealtimeCallback)

MethodParameterReturn valueDescription
public void onOpen()
NoneNoneThis method is called back immediately after the connection to the server is established.
public abstract void onEvent(JsonObject message)
message: the server response event.NoneIncludes responses to API calls and text and audio generated by the model. For details, see: Server events
public abstract void onClose(int code, String reason)
code: the status code of the WebSocket closure.reason: the close reason of the WebSocket.NoneCalled back after the server has closed the connection.