Skip to main content
Realtime API

Synthesize speech with qwen-audio-3.1-tts-flash over AOQ

Use qwen-audio-3.1-tts-flash over AOQ to synthesize text in segments and buffer and play the resulting PCM audio in an Android app.

Solution overview

TTS typically generates and delivers audio faster than it plays. When synthesizing long passages, the client buffers much of the audio before playing it. If you use the SDK player, the playback path closes when the server disconnects after about 60 seconds of inactivity. Audio left in its buffer may not play. This solution uses the following approach:
  1. Use onReceivedAudioFrame, introduced in SDK 1.4.2, to deliver incoming PCM to the app without waiting for SDK playback.
  2. Start the SDK player in external mode. Configure PCM output and subscribe to the Audio track in Segment mode. The SDK sends no sound to the device; the app plays its own queue.
  3. The app manages buffering, playback progress, pause, resume, and stop. Do not stop the app player or clear it when the connection closes or the engine is destroyed. Audio already saved can still play.
  4. To synthesize more audio after disconnection, obtain fresh credentials and reconnect. The app decides whether to keep or discard existing audio and how to append the new audio.

Prerequisites

  1. Activate QwenCloud and get an API key in the console. Store the API key only on your application server (AppServer). Do not include it in client code or commit it to a repository.
  2. Confirm the AOQ endpoint for the region in which your application is deployed. For selection guidance, see Select a region, deployment scope, and endpoint.
  3. Get the AOQ Client SDK from SDK download. Use version 1.4.2 or later with the incoming audio callback. Version 1.4.1 and earlier do not meet this requirement.
  4. Set up an AppServer by following the AOQ authentication steps for Qwen-Audio-TTS. Before each new connection, the client must obtain new connection credentials from the AppServer.

Import the SDK

Import the SDK for your platform. The callback and client examples below use Android Java. For callback signatures and audio buffer lifetimes on other platforms, see the respective SDK reference. PCM output does not require the Opus plugin.

Android

  1. Place AoqClientSdk-release.aar in app/libs/ and configure the dependency and ABIs in app/build.gradle:
android {
    defaultConfig {
        minSdk 21
        ndk { abiFilters 'armeabi-v7a', 'arm64-v8a' }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.aar'])
}
  1. Declare the following permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  1. This scenario does not require microphone or camera permissions.

iOS

  1. Add AoqClientSdk.framework to the Xcode project and select Embed & Sign under General > Frameworks, Libraries, and Embedded Content. Use an arm64 device running iOS 13.0 or later.
  2. This scenario does not use the microphone or camera and requires no related permissions.
  3. Use import AoqClientSdk in Swift or #import <AoqClientSdk/AoqClientSdk.h> in Objective-C.

HarmonyOS

  1. Place AoqClientSdk.har in entry/libs/ and declare the dependency in entry/oh-package.json5. Use an arm64-v8a device with API 12 or later:
{
  "dependencies": {
    "@aoq/client-sdk": "file:./libs/AoqClientSdk.har"
  }
}
  1. Declare the following permissions in entry/src/main/module.json5:
{
  "requestPermissions": [
    { "name": "ohos.permission.INTERNET" }
  ]
}
  1. This scenario does not require microphone or camera permissions.

Implementation flow

  1. The AppServer requests AOQ connection parameters for qwen-audio-3.1-tts-flash from the inference token endpoint and returns them to the client.
  2. The client creates the engine, registers and enables the incoming audio callback, and starts the SDK player in external mode. It configures PCM decoding, subscribes to the Audio track in Segment mode, publishes and subscribes to the Data track, and connects.
  3. After connecting, use a new task_id to send run-task. Once task-started arrives, send one or more continue-task text segments as needed.
  4. The SDK delivers incoming PCM to the app through onReceivedAudioFrame. Enqueue it promptly and play it with AudioTrack on a separate thread. Local playback does not determine the receive rate.
  5. After sending all text, send finish-task. The server continues to deliver the remaining audio and events. When task-finished arrives, update the task state without stopping the player or immediately disabling the audio callback.
  6. On disconnection, mark local input as ended. Continue playing data in the queue and in AudioTrack. Report playback completion only after input has ended and all buffered data has played.
  7. For another synthesis task, use a new task_id if still connected. Otherwise, obtain fresh credentials and reconnect. Release the engine when no longer needed. Close the app player separately when playback finishes or the user leaves.
The diagram shows the main flow. The app buffers and plays audio internally, shown as calls to itself. The implementation steps below give the order of client events.
Implementation flow: AOQ / PCM

Obtain a token from the application server

Set DASHSCOPE_API_KEY on the AppServer and send the request to the endpoint for your region. clientIp is the client's public IP address. Providing it helps the service choose a suitable relay endpoint, but it is optional. If you send the public IP address, set CLIENT_REAL_IP to it.
# Singapore (ap-southeast-1). For another region, replace ap-southeast-1 in the URL.
# API keys are region-specific. See https://docs.qwencloud.com/developer-guides/getting-started/regions
curl -X POST \
  "https://ap-southeast-1.maas.qwencloudapi.com/api/v1/webrtc/inference?model=qwen-audio-3.1-tts-flash" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${DASHSCOPE_API_KEY}" \
  -H "x-dashscope-rtc-transport: moq" \
  -d "{\"clientIp\": \"${CLIENT_REAL_IP:?}\"}"
If the AppServer cannot obtain the client's public IP address, omit clientIp instead of passing an empty string. Return the following response fields to the client. Keep the API key on the AppServer.
Response fieldSDK field
aoqTokenForClientAoqConnectConfig.token
sidAoqConnectConfig.sid
clientRelayCertFingerprintAoqConnectConfig.certFingerprint
clientRelayEndpointsAoqConnectConfig.relayEndpoints
extraInfo.workspaceIdHashAoqConnectConfig.workspaceIdHash

Implement the Android client

After obtaining AoqConnectConfig from the AppServer, follow these steps. In the snippets, main is a main-thread Handler and player is the app's PcmPlayer instance. See the Complete example for the assembled classes.

Create the engine and register callbacks

Create the singleton AOQ engine and register callbacks for connection state, Data track messages, and errors. SDK callbacks run on internal threads. The example dispatches connection state changes and task events to the main thread.
AoqClientListener listener = new AoqClientListener() {
    @Override
    public void onConnectionStatusChange(AoqClientEngine.AoqConnectionStatus status) {
        main.post(() -> handleConnectionStatus(status));
    }

    @Override
    public void onDataMsg(AoqClientEngine.AoqDataMsg msg) {

        byte[] data = msg.data;

        main.post(() -> handleServerEvent(data));
    }

    @Override
    public void onError(int code, String message) {
        Log.e(TAG, "onError code=" + code + " message=" + message);
    }
};

AoqClientEngine.AoqCreateConfig createConfig = new AoqClientEngine.AoqCreateConfig();
createConfig.workDir = context.getFilesDir().getAbsolutePath();
engine = AoqClientEngine.createEngine(context, createConfig, listener);

Register the PCM receive callback

Register the observer with setAudioFrameObserver, then use enableAudioFrameObserver to enable AoqAudioSourceReceived. Configure the observer before calling connect; do not rely on enabling it after connecting.
engine.setAudioFrameObserver(new AoqClientListener.AoqAudioFrameListener() {
    @Override
    public void onReceivedAudioFrame(AoqClientEngine.AoqTrackType trackType,
                                     AoqClientEngine.AoqAudioFrameData frame) {
        // Enqueue only. Do not block or call SDK methods here.
        try {
            if (trackType != AoqClientEngine.AoqTrackType.AoqTrackTypeAudio) return;
            if (frame.dataPtr == null || frame.dataSize <= 0 || frame.bytesPerSample != 2) return;
            player.enqueue(frame.samplesPerSec, frame.numOfChannels, frame.dataPtr, frame.dataSize);
        } catch (RuntimeException e) {
            Log.e(TAG, "enqueue pcm failed", e);
        }
    }
});

AoqClientEngine.AoqAudioObserverConfig observerConfig = new AoqClientEngine.AoqAudioObserverConfig();
observerConfig.sampleRate = 24000;  // Match sample_rate in run-task.
observerConfig.channels = 1;
observerConfig.mode = AoqClientEngine.AoqAudioObserverMode.AoqAudioObserverModeReadOnly;
int ret = engine.enableAudioFrameObserver(true,
        AoqClientEngine.AoqAudioSource.AoqAudioSourceReceived, observerConfig);
if (ret != 0) {
    throw new IllegalStateException("enableAudioFrameObserver failed: " + ret);
}
Parameters of AoqAudioObserverConfig:
ParameterDescription
sampleRateCallback sample rate. Match the run-task parameter sample_rate to avoid resampling.
channelsNumber of callback audio channels. This example uses one.
modeIncoming audio is read-only. Set the mode to AoqAudioObserverModeReadOnly. Even in read/write mode, changes to the data are not written back to the SDK.
Parameters of onReceivedAudioFrame:
ParameterDescription
trackTypeAudio track type. This example handles only AoqTrackTypeAudio.
framePCM data for this callback. The fields are listed below.
Main fields of AoqAudioFrameData:
FieldDescription
dataPtr16-bit interleaved PCM. Android Java supplies a separate byte[]. The app can retain the array after the callback without an extra copy. This does not apply to native pointers on other platforms.
dataSizeNumber of PCM bytes in this callback.
numOfSamplesSamples per channel in this callback. Use the actual count to calculate duration.
bytesPerSampleBytes per sample; two in this example.
numOfChannelsNumber of channels in the callback audio.
samplesPerSecSample rate of the callback audio.
timeStampTimestamp in milliseconds. Enqueue in callback order; do not infer playback progress from task events.
Incoming audio callback restrictions:
  1. Only PCM output with the Audio track in Segment mode is supported. The output is 16-bit PCM. The callback does not deliver Opus or Stream-mode audio.
  2. The receive callback is independent of the SDK playback clock. Do not also enable an unused playback callback, which may keep the SDK playback buffer active.
  3. One callback does not necessarily correspond to one network packet. Use dataSize and numOfSamples rather than packet length. Do not assume that a partial frame at the end of a sentence will be delivered later.
  4. The callback runs on an SDK thread. Only enqueue data there. Do not call SDK methods such as enableAudioFrameObserver, setAudioFrameObserver, disconnect, or destroy, or wait for the main thread: this can deadlock.
  5. Only PCM already saved by the app can play after disconnection. Audio not yet received or delivered through the callback is not in the local buffer. For sample-exact reproduction of model output, verify the audio boundaries and completeness separately.

Start the player in external mode

The app plays audio, but it must still call startAudioPlayer with isExternal set to true. The SDK does not send sound to the device. In this receive path, application Data messages need not wait for SDK playback either.
AoqClientEngine.AoqAudioPlaybackConfig playbackConfig = new AoqClientEngine.AoqAudioPlaybackConfig();
playbackConfig.isExternal = true;
playbackConfig.channel = 1;
engine.startAudioPlayer(playbackConfig);
Do not skip this step or set isExternal to false. Timestamped task events could wait for SDK playback, or both players could output sound. The app selects its own output device, such as the speaker or earpiece.

Configure the decoder and tracks and connect

Match these three settings:
  1. In setAudioDecoderConfig, set codecType to AoqEncoderTypeAudioPCM.
  2. When subscribing to the Audio track, set trackMode to AoqTrackModeSegment.
  3. In run-task, set format to pcm and match sample_rate to the decoder sample rate.
AoqClientEngine.AoqAudioCodecConfig audioDecoderConfig = new AoqClientEngine.AoqAudioCodecConfig();
audioDecoderConfig.trackType = AoqClientEngine.AoqTrackType.AoqTrackTypeAudio;
audioDecoderConfig.codecType = AoqClientEngine.AoqEncoderType.AoqEncoderTypeAudioPCM;
audioDecoderConfig.sampleRate = 24000;
audioDecoderConfig.channel = 1;
engine.setAudioDecoderConfig(audioDecoderConfig);

AoqClientEngine.AoqTrackParam publishDataTrack = new AoqClientEngine.AoqTrackParam();
publishDataTrack.trackType = AoqClientEngine.AoqTrackType.AoqTrackTypeData;
connectConfig.publishTracks.add(publishDataTrack);

AoqClientEngine.AoqTrackParam subscribeAudioTrack = new AoqClientEngine.AoqTrackParam();
subscribeAudioTrack.trackType = AoqClientEngine.AoqTrackType.AoqTrackTypeAudio;
subscribeAudioTrack.trackMode = AoqClientEngine.AoqTrackMode.AoqTrackModeSegment;
connectConfig.subscribeTracks.add(subscribeAudioTrack);

AoqClientEngine.AoqTrackParam subscribeDataTrack = new AoqClientEngine.AoqTrackParam();
subscribeDataTrack.trackType = AoqClientEngine.AoqTrackType.AoqTrackTypeData;
connectConfig.subscribeTracks.add(subscribeDataTrack);

engine.connect(connectConfig);
Enabling the callback alone does not enable this path. Without both PCM and Segment mode, the callback may deliver no audio even if the connection succeeds; there is no fixed error code. Check the actual output format, callback delivery, and SDK logs.

Call sendDataMsg to send a run-task event

After connecting, generate a new UUID for task_id. Configure the model, voice, text type, audio format, and sample rate. Set format to pcm and match sample_rate to the decoder. For optional parameters, see Client events.
taskId = UUID.randomUUID().toString();
JSONObject header = new JSONObject()
        .put("action", "run-task")
        .put("task_id", taskId)
        .put("streaming", "duplex");
JSONObject parameters = new JSONObject()
        .put("text_type", "PlainText")
        .put("voice", voice)
        .put("format", "pcm")
        .put("sample_rate", 24000);
JSONObject payload = new JSONObject()
        .put("task_group", "audio")
        .put("task", "tts")
        .put("function", "SpeechSynthesizer")
        .put("model", "qwen-audio-3.1-tts-flash")
        .put("input", new JSONObject())
        .put("parameters", parameters);
JSONObject runTask = new JSONObject().put("header", header).put("payload", payload);
AoqClientEngine.AoqDataMsg dataMessage = new AoqClientEngine.AoqDataMsg();
dataMessage.data = runTask.toString().getBytes(StandardCharsets.UTF_8);
engine.sendDataMsg(dataMessage);

Call sendDataMsg to send a continue-task event

Wait for task-started before sending continue-task. Each segment can contain up to 20,000 characters, up to 200,000 in total. Use the same ID for run-task, continue-task, and finish-task in task_id. Send the next segment or end the task promptly instead of relying on a fixed connection timeout.
JSONObject continueHeader = new JSONObject()
        .put("action", "continue-task")
        .put("task_id", taskId)
        .put("streaming", "duplex");
JSONObject payload = new JSONObject()
        .put("input", new JSONObject().put("text", text));
JSONObject continueTask = new JSONObject()
        .put("header", continueHeader)
        .put("payload", payload);
AoqClientEngine.AoqDataMsg dataMessage = new AoqClientEngine.AoqDataMsg();
dataMessage.data = continueTask.toString().getBytes(StandardCharsets.UTF_8);
engine.sendDataMsg(dataMessage);

Handle server events

In onDataMsg, read header.event to track task state and handle failures. result-generated returns sentence metadata; the audio arrives on the Audio track and reaches the app through onReceivedAudioFrame. For all fields, see Server events.
JSONObject header = new JSONObject(new String(data, StandardCharsets.UTF_8)).optJSONObject("header");
if (header == null) return;
String name = header.optString("event");
if ("task-started".equals(name)) {
    // Send one or more continue-task events.
} else if ("result-generated".equals(name)) {
    // Sentence metadata; do not advance playback here.
} else if ("task-finished".equals(name)) {
    taskActive = false;
    // Update the task state only. Do not stop playback or mark input as ended.
} else if ("task-failed".equals(name)) {
    taskActive = false;
    String message = header.optString("error_message");
    // Display or log the error. The app decides whether to stop and discard received audio.
}
The complete example calls player.markInputEnded() only after the connection reaches a terminal state or the connection and callback have been released. This ends local audio input; it does not prove that all model output has arrived. While connected, continue receiving and playing without waiting for disconnection. Do not end local input or report per-task playback completion based solely on task-finished.

Call sendDataMsg to send a finish-task event

Send finish-task immediately after the last text segment so that the server synthesizes any buffered partial sentence. Wait for subsequent audio and events. For details, see Client events.
JSONObject finishHeader = new JSONObject()
        .put("action", "finish-task")
        .put("task_id", taskId)
        .put("streaming", "duplex");
JSONObject finishTask = new JSONObject()
        .put("header", finishHeader)
        .put("payload", new JSONObject().put("input", new JSONObject()));
AoqClientEngine.AoqDataMsg dataMessage = new AoqClientEngine.AoqDataMsg();
dataMessage.data = finishTask.toString().getBytes(StandardCharsets.UTF_8);
engine.sendDataMsg(dataMessage);
Do not disconnect immediately after sending finish-task. Receiving task-finished does not mean playback is complete. Before releasing the connection early, ensure that doing so will not cut off audio in transit, or explicitly accept that reception will stop.

Buffer and play PCM

The app player must support the following:
  1. Fast enqueueing: Only enqueue PCM in the callback. Write to AudioTrack on a separate playback thread so that device writes do not block SDK callbacks.
  2. Independent lifetime: Do not clear the local queue or release the player when the connection closes or the engine is destroyed.
  3. Playback tracking: An empty queue does not mean the device has finished. Check that AudioTrack has played all samples written to it.
  4. Playback controls: The app implements pause, resume, and clear. To replay audio, save it separately; the playback queue is consumed.
The Complete example includes the PcmPlayer implementation. 24 kHz mono 16-bit PCM uses 48,000 bytes per second, about 2.75 MiB per minute. Set a memory budget for long passages. If buffered audio exceeds the budget, store it in a local file and read it for playback. Write files on a separate thread, not in the SDK callback.

Distinguish disconnection from playback completion

Distinguish these states:
StateConditionAction
Synthesis task endedtask-finished or task-failed receivedUpdate the task state. Do not stop playback or assume all audio callbacks have completed.
Local input endedConnection is Disconnected or Failed, or the app has released the connection and callbackCall markInputEnded() without clearing the queue.
Local playback endedInput has ended, the queue is empty, and AudioTrack has played all data written to itReport completion and release this AudioTrack.
private void handleConnectionStatus(AoqClientEngine.AoqConnectionStatus status) {
    if (status == AoqClientEngine.AoqConnectionStatus.AoqConnectionStatusConnected) {
        if (!closing && !connected) {
            connected = true;
            callback.onConnected(this);
        }
    } else if (status == AoqClientEngine.AoqConnectionStatus.AoqConnectionStatusDisconnected
            || status == AoqClientEngine.AoqConnectionStatus.AoqConnectionStatusFailed) {
        connectionEnded = true;
        connected = false;
        taskActive = false;
        if (closing) {
            finishClose();  // Release was requested. Unregister the observer and destroy the engine now.
        } else {
            player.markInputEnded();  // End local input and keep playing saved audio.
        }
    }
}
closing, connectionEnded, and finishClose() manage asynchronous release. See Complete example for the full definitions. Notes:
  1. Do not stop the app player or clear it on disconnection. A terminal connection state means no more audio will arrive on that connection, not that playback is complete.
  2. A network failure may occur before all audio arrives. Saved audio can still play; missing audio cannot be recovered this way.
  3. When the user stops playback, discard the audio: pause, clear local playback, stop retaining new audio, then end the connection asynchronously. Close the player according to the page lifecycle when the user leaves.

Start another synthesis after disconnection

The server disconnects after about 60 seconds of inactivity; the actual interval is determined by the server. With long passages, much of the audio may still be queued locally when synthesis ends, so the connection may close during playback. Do not send a new task on a closed connection or reuse its credentials. To continue:
  1. Release the old engine but keep the app player and its queue.
  2. Get new credentials from the AppServer.
  3. Recreate the engine, repeat the engine setup, and call connect.
  4. Once connected, send a new task_id with run-task. Append new audio after the existing queue or clear the old audio first, as appropriate.
// The connection has closed. Wait for the old singleton engine to be released before creating a new one.
private void synthesizeAfterDisconnect(String text, String voice) {
    client.close(() -> appServer.fetchConnectConfig(connectConfig -> main.post(() -> {
        client = new LongTtsClient(context, connectConfig, player, callback);
        pendingRequest = new Pair<>(text, voice);  // Call client.synthesize after the connection succeeds.
    })));
}
appServer.fetchConnectConfig and pendingRequest stand for the app's credential retrieval and pending-request logic. Implement them in the app; do not rely on the SDK to reconnect, resume old tasks, or decide when to clear buffered audio.

Disconnect and destroy the engine

When no more audio is needed, request disconnection. Wait for Disconnected or Failed before unregistering the callback and destroying the engine on the main thread. disconnect() is asynchronous: returning does not mean already received data has been processed. Do not immediately clear the observer or wait for disconnection on the SDK callback thread.
// If already disconnected, clean up now; otherwise keep the observer until a terminal state arrives.
closing = true;
if (connectionEnded) {
    finishClose();
} else {
    engine.disconnect();
}

// Run this from terminal-state handling on the main thread, not from the SDK callback thread.
private void finishClose() {
    engine.enableAudioFrameObserver(false,
            AoqClientEngine.AoqAudioSource.AoqAudioSourceReceived,
            new AoqClientEngine.AoqAudioObserverConfig());
    engine.setAudioFrameObserver(null);
    AoqClientEngine.destroy();
    player.markInputEnded();
}

// Destroying the engine does not stop local playback.
// Call player.close() after playback ends or the user leaves the page.
Disconnecting stops further network reception; it does not confirm that all audio arrived. The app manages its buffer and player separately.

Main server events

EventMeaningApp action
task-startedThe task has started; continue-task can be sentSubmit text.
result-generatedSentence metadata; audio arrives on the Audio trackRecord the result without advancing or ending local playback.
task-finishedAll buffered text has been processed and synthesis has endedUpdate the task state. Continue receiving and playing; do not end local input on this event alone.
task-failedTask failed; read the error code and messageDisplay or log the error. The app decides whether to continue playing or stop.

Complete example

The example includes two classes:
  1. LongTtsClient manages the engine, connection, and task events. Pass an AoqConnectConfig built from the AppServer token response to the constructor, then call synthesize(text, voice) when connected. Use the constructor and public methods on the main thread.
  2. PcmPlayer manages local buffering and playback independently of the connection. The callback submits PCM; the playback thread accesses the queue and device state. Call controls on the main thread. Completion is reported there, and an input generation counter filters out stale notifications after a clear or new input.
The example ends local input after the connection reaches a terminal state. close() only requests asynchronous closure. The callback passed to close(Runnable) runs after the old engine is released, so a new singleton can safely be created. While connected, new audio can be appended even after the queue drains. onPlaybackFinished does not report completion for each task_id. Some devices need a minimum amount of buffered audio to start. After input ends, the player adds silence without blocking until the playback head passes the last real frame. Silence does not count towards PCM duration. New input waits in the queue for a new track after the old AudioTrack is released. For production, handle UI state, storage and memory budgets for long audio, player errors, a stalled playback head, and new connections. Both classes can be saved in LongTtsClient.java. If you split them, keep the required imports in each file and use the same package.
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;


import com.alibaba.aoq.clientsdk.AoqClientEngine;
import com.alibaba.aoq.clientsdk.AoqClientListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.UUID;

public final class LongTtsClient {
    private static final String TAG = "LongTtsClient";
    private static final String MODEL = "qwen-audio-3.1-tts-flash";
    static final int SAMPLE_RATE = 24000;

    public interface Callback {
        void onConnected(LongTtsClient client);
        void onPlaybackFinished();
        void onTaskFailed(String message);
    }

    private final Handler main = new Handler(Looper.getMainLooper());
    private final PcmPlayer player;
    private final Callback callback;
    private AoqClientEngine engine;
    private String taskId;
    private String pendingText;
    private String pendingVoice;
    private boolean connected;
    private boolean taskActive;
    private boolean connectionEnded;
    private boolean closing;
    private boolean closed;
    private volatile boolean discardReceived;
    private Runnable afterClose;

    public LongTtsClient(Context context, AoqClientEngine.AoqConnectConfig connectConfig,
                         PcmPlayer player, Callback callback) {
        this.player = player;
        this.callback = callback;
        player.setOnFinishedListener(callback::onPlaybackFinished);

        AoqClientListener listener = new AoqClientListener() {
            @Override
            public void onConnectionStatusChange(AoqClientEngine.AoqConnectionStatus status) {
                main.post(() -> {
                    if (!closed) handleConnectionStatus(status);
                });
            }

            @Override
            public void onDataMsg(AoqClientEngine.AoqDataMsg msg) {

                byte[] data = msg.data;

                main.post(() -> {
                    if (!closed && !closing) handleServerEvent(data);
                });
            }

            @Override
            public void onError(int code, String message) {
                Log.e(TAG, "onError code=" + code + " message=" + message);
            }
        };

        AoqClientEngine.AoqCreateConfig createConfig = new AoqClientEngine.AoqCreateConfig();
        createConfig.workDir = context.getFilesDir().getAbsolutePath();
        engine = AoqClientEngine.createEngine(context, createConfig, listener);

        // Enable incoming audio callbacks before connecting.
        engine.setAudioFrameObserver(new AoqClientListener.AoqAudioFrameListener() {
            @Override
            public void onReceivedAudioFrame(AoqClientEngine.AoqTrackType trackType,
                                             AoqClientEngine.AoqAudioFrameData frame) {
                try {
                    if (discardReceived) return;  // Do not retain audio after the user explicitly stops playback.
                    if (trackType != AoqClientEngine.AoqTrackType.AoqTrackTypeAudio) return;
                    if (frame.dataPtr == null || frame.dataSize <= 0 || frame.bytesPerSample != 2) return;
                    player.enqueue(frame.samplesPerSec, frame.numOfChannels, frame.dataPtr, frame.dataSize);
                } catch (RuntimeException e) {
                    Log.e(TAG, "enqueue pcm failed", e);
                }
            }
        });
        AoqClientEngine.AoqAudioObserverConfig observerConfig = new AoqClientEngine.AoqAudioObserverConfig();
        observerConfig.sampleRate = SAMPLE_RATE;
        observerConfig.channels = 1;
        observerConfig.mode = AoqClientEngine.AoqAudioObserverMode.AoqAudioObserverModeReadOnly;
        int ret = engine.enableAudioFrameObserver(true,
                AoqClientEngine.AoqAudioSource.AoqAudioSourceReceived, observerConfig);
        if (ret != 0) throw new IllegalStateException("enableAudioFrameObserver failed: " + ret);

        // External playback: the SDK outputs no sound, and Data messages do not wait for SDK playback.
        AoqClientEngine.AoqAudioPlaybackConfig playbackConfig = new AoqClientEngine.AoqAudioPlaybackConfig();
        playbackConfig.isExternal = true;
        playbackConfig.channel = 1;
        engine.startAudioPlayer(playbackConfig);

        AoqClientEngine.AoqAudioCodecConfig audioDecoderConfig = new AoqClientEngine.AoqAudioCodecConfig();
        audioDecoderConfig.trackType = AoqClientEngine.AoqTrackType.AoqTrackTypeAudio;
        audioDecoderConfig.codecType = AoqClientEngine.AoqEncoderType.AoqEncoderTypeAudioPCM;
        audioDecoderConfig.sampleRate = SAMPLE_RATE;
        audioDecoderConfig.channel = 1;
        engine.setAudioDecoderConfig(audioDecoderConfig);

        AoqClientEngine.AoqTrackParam publishDataTrack = new AoqClientEngine.AoqTrackParam();
        publishDataTrack.trackType = AoqClientEngine.AoqTrackType.AoqTrackTypeData;
        connectConfig.publishTracks.add(publishDataTrack);

        AoqClientEngine.AoqTrackParam subscribeAudioTrack = new AoqClientEngine.AoqTrackParam();
        subscribeAudioTrack.trackType = AoqClientEngine.AoqTrackType.AoqTrackTypeAudio;
        subscribeAudioTrack.trackMode = AoqClientEngine.AoqTrackMode.AoqTrackModeSegment;
        connectConfig.subscribeTracks.add(subscribeAudioTrack);

        AoqClientEngine.AoqTrackParam subscribeDataTrack = new AoqClientEngine.AoqTrackParam();
        subscribeDataTrack.trackType = AoqClientEngine.AoqTrackType.AoqTrackTypeData;
        connectConfig.subscribeTracks.add(subscribeDataTrack);

        engine.connect(connectConfig);
    }

    /** Call on the main thread to start synthesis when connected and no task is active. */
    public void synthesize(String text, String voice) {
        if (!connected || taskActive) {
            throw new IllegalStateException("The connection is not ready or a task is active.");
        }
        taskId = UUID.randomUUID().toString();
        pendingText = text;
        pendingVoice = voice;
        taskActive = true;
        player.beginInput();
        sendRunTask();
    }

    /** Call on the main thread to request an immediate playback stop and end the connection asynchronously. */
    public void stop() {
        if (closed) {
            player.clear();
            player.setPaused(false);
            return;
        }
        discardReceived = true;
        player.setPaused(true);
        player.clear();
        close();
    }

    /** Call on the main thread to release the connection and engine asynchronously. Saved audio continues to play. */
    public void close() {
        close(null);
    }

    /** afterClose runs on the main thread after the old singleton is released, before creating a new engine. */
    public void close(Runnable afterClose) {
        if (closed) {
            if (afterClose != null) afterClose.run();
            return;
        }
        if (afterClose != null) this.afterClose = afterClose;
        if (closing) return;
        closing = true;
        connected = false;
        taskActive = false;
        if (connectionEnded) {
            finishClose();
        } else {
            engine.disconnect();  // Asynchronous: wait for the terminal-state callback before unregistering the observer.
        }
    }

    private void finishClose() {
        if (closed) return;
        closed = true;
        engine.enableAudioFrameObserver(false,
                AoqClientEngine.AoqAudioSource.AoqAudioSourceReceived,
                new AoqClientEngine.AoqAudioObserverConfig());
        engine.setAudioFrameObserver(null);
        AoqClientEngine.destroy();
        engine = null;
        if (discardReceived) {
            // Clear once more after draining to discard audio from callbacks already in flight at the stop request.
            player.clear();
            player.setPaused(false);
        } else {
            player.markInputEnded();
        }
        Runnable done = afterClose;
        afterClose = null;
        if (done != null) done.run();
    }

    private void handleConnectionStatus(AoqClientEngine.AoqConnectionStatus status) {
        if (status == AoqClientEngine.AoqConnectionStatus.AoqConnectionStatusConnected) {
            if (!closing && !connected) {
                connected = true;
                callback.onConnected(this);
            }
        } else if (status == AoqClientEngine.AoqConnectionStatus.AoqConnectionStatusDisconnected
                || status == AoqClientEngine.AoqConnectionStatus.AoqConnectionStatusFailed) {
            connectionEnded = true;
            connected = false;
            taskActive = false;
            if (closing) {
                finishClose();
            } else {
                player.markInputEnded();
            }
        }
    }


    private void handleServerEvent(byte[] data) {

        try {
            JSONObject header = new JSONObject(new String(data, StandardCharsets.UTF_8))
                    .optJSONObject("header");
            if (header == null) return;
            String incomingTaskId = header.optString("task_id", "");
            if (!incomingTaskId.isEmpty() && !incomingTaskId.equals(taskId)) return;
            String event = header.optString("event");
            if ("task-started".equals(event)) {
                sendContinueTask();
                sendFinishTask();
            } else if ("task-finished".equals(event)) {
                taskActive = false;
                // A task event is not an audio reception barrier. Do not call markInputEnded here.
            } else if ("task-failed".equals(event)) {
                taskActive = false;
                callback.onTaskFailed(header.optString("error_message"));
            }
        } catch (JSONException e) {
            Log.w(TAG, "Invalid server event", e);
        }
    }

    private void sendRunTask() {
        try {
            JSONObject parameters = new JSONObject()
                    .put("text_type", "PlainText")
                    .put("voice", pendingVoice)
                    .put("format", "pcm")
                    .put("sample_rate", SAMPLE_RATE);
            JSONObject payload = new JSONObject()
                    .put("task_group", "audio")
                    .put("task", "tts")
                    .put("function", "SpeechSynthesizer")
                    .put("model", MODEL)
                    .put("input", new JSONObject())
                    .put("parameters", parameters);
            send(header("run-task"), payload);
        } catch (JSONException e) {
            throw new IllegalStateException("Failed to create run-task", e);
        }
    }

    private void sendContinueTask() {
        try {
            send(header("continue-task"),
                    new JSONObject().put("input", new JSONObject().put("text", pendingText)));
        } catch (JSONException e) {
            throw new IllegalStateException("Failed to create continue-task", e);
        }
    }

    private void sendFinishTask() {
        try {
            send(header("finish-task"), new JSONObject().put("input", new JSONObject()));
        } catch (JSONException e) {
            throw new IllegalStateException("Failed to create finish-task", e);
        }
    }

    private JSONObject header(String action) throws JSONException {
        return new JSONObject()
                .put("action", action)
                .put("task_id", taskId)
                .put("streaming", "duplex");
    }

    private void send(JSONObject header, JSONObject payload) throws JSONException {
        AoqClientEngine.AoqDataMsg dataMessage = new AoqClientEngine.AoqDataMsg();
        dataMessage.data = new JSONObject().put("header", header).put("payload", payload)
                .toString().getBytes(StandardCharsets.UTF_8);
        engine.sendDataMsg(dataMessage);
    }
}

/** Local PCM buffering and playback. Access internal playback state on the playback thread. */
final class PcmPlayer implements AutoCloseable {
    private static final String TAG = "PcmPlayer";
    private static final int CHANNEL_MASK = AudioFormat.CHANNEL_OUT_MONO;
    private static final int ENCODING = AudioFormat.ENCODING_PCM_16BIT;

    private final int sampleRate;
    private final HandlerThread thread = new HandlerThread("tts-local-playout");
    private final Handler worker;
    private final Handler main = new Handler(Looper.getMainLooper());
    private final ArrayDeque<ByteBuffer> queue = new ArrayDeque<>();
    private final ByteBuffer finishSilence = ByteBuffer.allocate(2048);
    private final Runnable pump = this::pump;
    private volatile boolean closed;
    private Runnable onFinished;
    private long inputGeneration;  // Accessed on the main thread to invalidate stale completion notifications.
    private long workerGeneration; // Accessed on the playback thread to identify the current input.
    private boolean tailDraining;

    private AudioTrack track;
    private long writtenFrames;
    private boolean inputEnded = true;
    private boolean finishNotified = true;
    private boolean paused;
    private boolean pumpScheduled;

    PcmPlayer(int sampleRate) {
        this.sampleRate = sampleRate;
        thread.start();
        worker = new Handler(thread.getLooper());
    }

    void setOnFinishedListener(Runnable listener) {
        worker.post(() -> onFinished = listener);
    }

    /** May be called from the SDK callback thread; only posts data to the playback thread. */

    void enqueue(int frameSampleRate, int channels, byte[] pcm, int byteCount) {

        if (closed || frameSampleRate != sampleRate || channels != 1 || byteCount <= 0
                || byteCount > pcm.length || (byteCount & 1) != 0) return;
        worker.post(() -> {
            if (closed) return;
            queue.addLast(ByteBuffer.wrap(pcm, 0, byteCount));
            schedulePump(0);
        });
    }

    /** Call on the main thread to begin new input while retaining audio still queued from the previous input. */
    void beginInput() {
        long generation = ++inputGeneration;
        worker.post(() -> {
            workerGeneration = generation;
            inputEnded = false;
            finishNotified = false;
        });
    }

    /** Call when no more audio can arrive for this input. Keep the queue. */
    void markInputEnded() {
        worker.post(() -> {
            inputEnded = true;
            schedulePump(0);
        });
    }

    void setPaused(boolean pause) {
        worker.post(() -> {
            paused = pause;
            if (pause && track != null) track.pause();
            if (!pause) schedulePump(0);
        });
    }

    /** Call on the main thread to discard all audio and invalidate stale completion notifications. */
    void clear() {
        ++inputGeneration;
        worker.post(() -> {
            worker.removeCallbacks(pump);
            pumpScheduled = false;
            queue.clear();
            inputEnded = true;
            finishNotified = true;
            releaseTrack();
        });
    }

    @Override
    public void close() {
        if (closed) return;
        ++inputGeneration;
        closed = true;
        worker.post(() -> {
            worker.removeCallbacks(pump);
            queue.clear();
            releaseTrack();
            thread.quitSafely();
        });
    }

    private void schedulePump(long delayMs) {
        if (pumpScheduled || paused || closed) return;
        pumpScheduled = true;
        worker.postDelayed(pump, delayMs);
    }

    private void pump() {
        pumpScheduled = false;
        if (closed || paused) return;
        try {
            if (!queue.isEmpty() && track == null) track = createTrack();
            if (track == null) {
                if (inputEnded) notifyFinishedOnce();
                return;
            }
            if (track.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) track.play();
            if (tailDraining) {
                drainTail();
                return;
            }
            // Write at most about 100 ms of mono 16-bit PCM at a time.
            int budget = sampleRate / 5;
            while (budget > 0 && !queue.isEmpty()) {
                ByteBuffer head = queue.getFirst();
                int written = track.write(head, Math.min(head.remaining(), budget),
                        AudioTrack.WRITE_NON_BLOCKING);
                if (written < 0) throw new IllegalStateException("AudioTrack.write: " + written);
                if (written == 0) break;
                writtenFrames += written / 2;
                budget -= written;
                if (!head.hasRemaining()) queue.removeFirst();
            }
            if (inputEnded && queue.isEmpty()) {
                tailDraining = true;
                drainTail();
                return;
            }
            long playedFrames = track.getPlaybackHeadPosition() & 0xffffffffL;
            if (queue.isEmpty() && playedFrames >= writtenFrames) {
                track.pause();
                return;  // Input is still open. The next enqueue drives playback again.
            }
        } catch (RuntimeException e) {
            Log.e(TAG, "Local playback failed", e);
            releaseTrack();
            return;
        }
        schedulePump(10);
    }

    /** After input ends, pad with silence to meet the device threshold. Count only real PCM in writtenFrames. */
    private void drainTail() {
        long playedFrames = track.getPlaybackHeadPosition() & 0xffffffffL;
        if (playedFrames >= writtenFrames) {
            releaseTrack();
            if (inputEnded && queue.isEmpty()) notifyFinishedOnce();
            if (!queue.isEmpty()) schedulePump(0);
            return;
        }
        finishSilence.clear();
        int n = track.write(finishSilence, finishSilence.remaining(),
                AudioTrack.WRITE_NON_BLOCKING);
        if (n < 0) throw new IllegalStateException("AudioTrack padding write: " + n);
        // Do not count padding in writtenFrames. Keep new input queued until the old track drains, then create a new track.
        schedulePump(10);
    }

    /** Recheck the generation before notifying on the main thread to suppress stale notifications after clear or new input. */
    private void notifyFinishedOnce() {
        if (finishNotified) return;
        finishNotified = true;
        long generation = workerGeneration;
        Runnable listener = onFinished;
        main.post(() -> {
            if (!closed && generation == inputGeneration && listener != null) listener.run();
        });
    }

    private AudioTrack createTrack() {
        int minBytes = AudioTrack.getMinBufferSize(sampleRate, CHANNEL_MASK, ENCODING);
        if (minBytes <= 0) throw new IllegalStateException("Unsupported PCM output");
        AudioTrack output = new AudioTrack(
                new AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                        .build(),
                new AudioFormat.Builder()
                        .setSampleRate(sampleRate)
                        .setChannelMask(CHANNEL_MASK)
                        .setEncoding(ENCODING)
                        .build(),
                Math.max(minBytes, sampleRate / 5), AudioTrack.MODE_STREAM,
                AudioManager.AUDIO_SESSION_ID_GENERATE);
        if (output.getState() != AudioTrack.STATE_INITIALIZED) {
            output.release();
            throw new IllegalStateException("AudioTrack initialization failed");
        }
        writtenFrames = 0;
        return output;
    }

    private void releaseTrack() {
        if (track != null) {
            track.release();
            track = null;
        }
        writtenFrames = 0;
        tailDraining = false;
    }
}
Usage:
// Create on the main thread. The player follows the page lifetime, not the connection.
PcmPlayer player = new PcmPlayer(LongTtsClient.SAMPLE_RATE);
LongTtsClient.Callback callback = new LongTtsClient.Callback() {
    @Override public void onConnected(LongTtsClient session) {
        // Use a supported system voice or a valid voice_id.
        session.synthesize(text, voice);
    }
    @Override public void onPlaybackFinished() { Log.i("TTS", "Playback complete"); }
    @Override public void onTaskFailed(String message) { Log.e("TTS", message); }
};
LongTtsClient client = new LongTtsClient(context, connectConfig, player, callback);


// Pause or resume without interrupting incoming audio.
// player.setPaused(true);
// player.setPaused(false);

// When the user stops: client.stop();
// When leaving the page:
// client.close();
// player.close();
For all parameters, event fields, and interfaces for other platforms, see:
  1. Obtain and configure an API key
  2. Select a region, deployment scope, and endpoint
  3. AOQ Client SDK overview
  4. SDK download
  5. Qwen-Audio-TTS AOQ access
  6. Qwen-Audio-TTS user guide
  7. Client events
  8. Server events