Speech synthesis best practices

Updated at:

Apply speech synthesis best practices for text submission, audio processing, connection and concurrency resource management, performance evaluation, and troubleshooting.

Text submission and task control

When using a cloned or designed voice, the synthesis model must match the target model specified when the voice was created. See Voice cloning or Voice design for voice creation requirements.

Text segmentation and submission timing

For Qwen-Audio-TTS and CosyVoice over WebSocket, wait for task-started before sending text segments in order. The server segments the text automatically: complete sentences are synthesized immediately; incomplete sentences are buffered until completed or until finish-task arrives.

Long intervals between text segments increase total synthesis time. Playback can also stall if the previous audio finishes before the next text segment arrives. See Qwen-Audio-TTS client events or CosyVoice client events for per-segment, cumulative length, and submission interval limits.

NoteSubmit the complete SSML text at once. Segmented input is not supported for SSML. See SSML and LaTeX for supported models, voices, and interfaces.

Task completion and cancellation

When calling Qwen-Audio-TTS or CosyVoice through the raw WebSocket protocol, after sending all text, send finish-task to end input and continue receiving audio until task-finished. Omitting the end-of-input notification can result in incomplete audio.

To interrupt the current synthesis task, use task cancellation. The server ends the task and returns task-finished. See Cancel a task for SDK and raw protocol usage and applicability.

Audio reception and playback

Audio reception and storage

Qwen-Audio-TTS and CosyVoice return audio differently depending on the interface:

  • Non-streaming HTTP output: Download the complete audio file from output.audio.url. The URL is valid for 24 hours. Save the file before it expires; you can synthesize the audio again after expiration.
  • HTTP SSE output: output.audio.data contains Base64-encoded audio segments. Decode them in reception order and append them to the same file. See the Qwen-Audio-TTS HTTP API and CosyVoice HTTP API for response fields.
  • Raw WebSocket protocol: Receive audio through the binary channel. Text events carry sentence information and other metadata. See the Qwen-Audio-TTS WebSocket API and CosyVoice WebSocket API for the interaction flow.

Audio format and player compatibility

When saving a complete audio file, match the file extension to the requested audio format and verify that the player supports the format and sample rate. To troubleshoot streaming playback, first save the stream as a complete file. If the file cannot play, check the format and player. If the file plays correctly, check whether the playback implementation supports streaming audio, such as ffmpeg, pyaudio, AudioFormat, or MediaSource.

For streamed WAV output, the header might not reflect the final audio length. If accurate duration is required, set format to pcm, receive the complete audio, and add a WAV header containing the actual length.

Callback and playback scheduling

Real-time synthesis callbacks run on the WebSocket thread. Blocking business logic can delay audio reception. Write audio to a separate buffer and process it on another thread. For playback stalls, also check text submission speed and network stability: network fluctuations can interrupt or delay audio delivery.

Connection and concurrency resource management

Connection reuse and task isolation

When calling Qwen-Audio-TTS or CosyVoice through the raw WebSocket protocol, a connection can process multiple tasks sequentially. After task-finished, send run-task with a new task_id, then send text according to that model family’s flow. Follow the same sequence after cancellation.

For Qwen-Audio-TTS, CosyVoice, and Sambert, connections close after 60 seconds of inactivity following task completion. Evaluate the next call after a long idle period as a new connection.

With the Python SDK’s client.audio.tts.connect, a session closes its underlying connection by default when a task completes or is canceled. To reuse a connection, create a shared connection with client.ws_connection() and pass it to the session with connection=. The caller closes the shared connection with WsConnection.close.

Connection identity and isolation boundaries

The API key is sent in the Authorization header only during the WebSocket handshake. Later run-task messages do not carry it. Changing a key in parameters or global configuration does not change an existing connection's identity, which can assign identity, quota usage, or charges differently from what you expect.

Java SDK

In Java, create a separate pool for each API key and use the same key throughout each pool. For Qwen-Audio-TTS/CosyVoice, call updateParamAndCallback each time an object is borrowed. This method does not reauthenticate an existing connection.

Python SDK

In Python, set dashscope.api_key before creating the pool. Connections established during initialization retain the handshake key, and borrow_synthesizer has no API key parameter. SpeechSynthesizerObjectPool is a process-wide singleton, so isolate different keys in different processes.

Concurrency and resource planning

Object pools retain synthesis objects and their WebSocket connections to reduce object creation, TCP/TLS handshakes, and protocol upgrades. The following model series and SDKs support object pooling:

  • Qwen-Audio-TTS, CosyVoice: Python and Java object pools.
  • Sambert: Java object pools. The Python SDK does not provide an equivalent pool wrapper.

Configure resource pools for the expected number of simultaneous tasks and server capacity. Model limits apply to the Alibaba Cloud account and are shared by its RAM users, workspaces, and API keys. For model request-rate and concurrency limits, see Rate limits.

Start with a pool capacity of 1.5–2 times peak concurrency and adjust for the actual workload. The Python pool may create extra objects when all pooled objects are borrowed. These objects need new connections when used.

Server configuration reference

The following Alibaba Cloud server configurations are references for running only the indicated speech synthesis service. Per-server concurrency means simultaneous synthesis tasks. Adjust the configuration for the actual workload.

The connection pool setting in this table is a reference value for all three variables: DASHSCOPE_CONNECTION_POOL_SIZE, DASHSCOPE_MAXIMUM_ASYNC_REQUESTS, and DASHSCOPE_MAXIMUM_ASYNC_REQUESTS_PER_HOST. Set each to 2000 for these reference configurations. Set object pool capacity through the environment variable defined by the corresponding example.

SeriesAlibaba Cloud serverConcurrent tasksObject pool capacityConnection pool setting
CosyVoice4 vCPU / 8 GiB1005002000
CosyVoice8 vCPU / 16 GiB1505002000
CosyVoice16 vCPU / 32 GiB2005002000
Sambert4 vCPU / 8 GiB60012002000

Java resource pool parameters

Set SDK environment variables before starting the Java process. The first three variables are SDK settings; the pool capacity variables below them are defined by the examples:

Environment variableDefaultDescription
DASHSCOPE_CONNECTION_POOL_SIZE32The underlying OkHttp idle connection pool setting.
DASHSCOPE_MAXIMUM_ASYNC_REQUESTS32The maximum requests setting for the underlying asynchronous dispatcher.
DASHSCOPE_MAXIMUM_ASYNC_REQUESTS_PER_HOST32The per-host maximum requests setting for the underlying asynchronous dispatcher.
COSYVOICE_OBJECTPOOL_SIZE500Object pool capacity in the Qwen-Audio-TTS/CosyVoice Java example, used for maxTotal and maxIdle. This is not a built-in SDK parameter.
SAMBERT_OBJECTPOOL_SIZE500Object pool capacity in the Sambert Java example, used for maxTotal and maxIdle. This is not a built-in SDK parameter.

The Java examples set maxIdle equal to maxTotal to reduce object recreation after idle objects are destroyed. Close an object’s connection when destroying it. At maxTotal, new borrow requests wait for an available object.

Object lifecycle

Configure the API key and endpoint, then create a shared object pool for application tasks.

Java SDK

  1. Borrow an object with borrowObject. For Qwen-Audio-TTS/CosyVoice, call updateParamAndCallback(param, callback) each time an object is borrowed to set the task parameters and callback.
  2. Run Qwen-Audio-TTS/CosyVoice synthesis with call or streamingCall. Sambert uses call(param, callback) for one-way streaming synthesis.
  3. After normal completion, return the object with returnObject. If it is unfinished or failed, discard it with invalidateObject and let the factory close its connection; do not return it directly.
  4. After all tasks finish, call the pool’s close() to release pool resources.

In Java, when maxIdle is less than maxTotal, returned objects above the idle capacity are destroyed. If the factory's destroyObject does not close the WebSocket, the connection may remain open after the object is destroyed.

Python SDK

  1. Borrow an object with borrow_synthesizer, passing the model, voice, format, and callback.
  2. Run synthesis with call or streaming_call.
  3. After normal completion, return the object with return_synthesizer. If it is unfinished or failed, call the object’s close(); do not return it directly.
  4. After all tasks finish, call shutdown() to release pool resources.

After a client error interrupts a task, the server may still consider the previous task active. Reusing that connection for a new run-task causes a protocol sequence error (Invalid action('run-task')! Please follow the protocol!). Close the connection and discard the object, then establish a new connection for later tasks.

Frequently creating synthesis objects without closing old connections can continually increase connection counts and server resource usage. Check that objects are returned after task completion and unused connections are closed.

Object pool examples

  • Get an API key and set DASHSCOPE_API_KEY. Use a key for the region you call.
  • Replace {WorkspaceId} with the region’s workspace ID and configure its WebSocket endpoint.

Java SDK

  • Qwen-Audio-TTS, CosyVoice: DashScope Java SDK 2.16.6 or later.
  • Sambert: DashScope Java SDK 2.16.9 or later.

The Java examples also require Apache Commons Pool 2. Configure the dependencies with Maven or Gradle:

<dependencies>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>dashscope-sdk-java</artifactId>
        <version>2.23.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>2.12.0</version>
    </dependency>
</dependencies>
dependencies {
    implementation 'com.alibaba:dashscope-sdk-java:2.23.2'
    implementation 'org.apache.commons:commons-pool2:2.12.0'
}

Python SDK

Qwen-Audio-TTS and CosyVoice object pooling requires DashScope Python SDK 2.0.1 or later:

pip install "dashscope>=2.0.1"

Qwen-Audio-TTS/CosyVoice

The examples use qwen-audio-3.1-tts-flash and longanhuan_v3.1 for three concurrent synthesis tasks. For CosyVoice, change the model and voice to cosyvoice-v3-flash and longanyang. For other models and voice requirements, see Real-time speech synthesis.

import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisAudioFormat;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.utils.Constants;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;

public class PooledTts {
    static class Factory extends BasePooledObjectFactory<SpeechSynthesizer> {
        public SpeechSynthesizer create() { return new SpeechSynthesizer(); }
        public PooledObject<SpeechSynthesizer> wrap(SpeechSynthesizer value) {
            return new DefaultPooledObject<>(value);
        }
        public void destroyObject(PooledObject<SpeechSynthesizer> value) {
            value.getObject().getDuplexApi().close(1000, "done");
        }
    }

    static void synthesize(GenericObjectPool<SpeechSynthesizer> pool, int index) throws Exception {
        SpeechSynthesizer synthesizer = pool.borrowObject();
        boolean successful = false;
        AtomicReference<Exception> error = new AtomicReference<>();
        try (FileOutputStream audio = new FileOutputStream("output_" + index + ".mp3")) {
            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-audio-3.1-tts-flash")
                .voice("longanhuan_v3.1")
                .format(SpeechSynthesisAudioFormat.MP3_24000HZ_MONO_256KBPS)
                .build();
            synthesizer.updateParamAndCallback(param, new ResultCallback<SpeechSynthesisResult>() {
                public void onEvent(SpeechSynthesisResult result) {
                    ByteBuffer buffer = result.getAudioFrame();
                    if (buffer != null) {
                        byte[] bytes = new byte[buffer.remaining()];
                        buffer.get(bytes);
                        try { audio.write(bytes); }
                        catch (Exception e) { error.set(e); }
                    }
                }
                public void onComplete() {}
                public void onError(Exception e) { error.set(e); }
            });
            synthesizer.streamingCall("Hello, welcome to Alibaba Cloud Model Studio.");
            synthesizer.streamingComplete(60000);
            if (error.get() != null) { throw error.get(); }
            successful = true;
        } finally {
            if (successful) { pool.returnObject(synthesizer); }
            else { pool.invalidateObject(synthesizer); }
        }
    }

    public static void main(String[] args) throws Exception {
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference";
        GenericObjectPoolConfig<SpeechSynthesizer> config = new GenericObjectPoolConfig<>();
        int poolSize = Integer.parseInt(System.getenv().getOrDefault("COSYVOICE_OBJECTPOOL_SIZE", "500"));
        config.setMaxTotal(poolSize);
        config.setMaxIdle(poolSize);
        config.setMaxWait(Duration.ofSeconds(60));
        ExecutorService executor = Executors.newFixedThreadPool(3);
        try (GenericObjectPool<SpeechSynthesizer> pool = new GenericObjectPool<>(new Factory(), config)) {
            java.util.List<Future<?>> futures = new java.util.ArrayList<>();
            for (int i = 0; i < 3; i++) {
                final int index = i;
                futures.add(executor.submit(() -> {
                    try { synthesize(pool, index); }
                    catch (Exception e) { throw new RuntimeException(e); }
                }));
            }
            for (Future<?> future : futures) { future.get(); }
        } finally {
            executor.shutdownNow();
        }
    }
}
import os
import threading
from concurrent.futures import ThreadPoolExecutor
import dashscope
from dashscope.audio.tts_v2 import SpeechSynthesizerObjectPool, ResultCallback, AudioFormat

dashscope.api_key = os.environ["DASHSCOPE_API_KEY"]
dashscope.base_websocket_api_url = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference"
pool = SpeechSynthesizerObjectPool(max_size=3)

def synthesize(index):
    done = threading.Event()
    errors = []
    with open(f"output_{index}.mp3", "wb") as audio:
        class Callback(ResultCallback):
            def on_data(self, data: bytes):
                audio.write(data)

            def on_complete(self):
                done.set()

            def on_error(self, message):
                errors.append(message)
                done.set()

        synthesizer = pool.borrow_synthesizer(
            model="qwen-audio-3.1-tts-flash",
            voice="longanhuan_v3.1",
            format=AudioFormat.MP3_24000HZ_MONO_256KBPS,
            callback=Callback(),
        )
        successful = False
        try:
            synthesizer.streaming_call("Hello, welcome to Alibaba Cloud Model Studio.")
            synthesizer.streaming_complete(60000)
            if not done.wait(60):
                raise TimeoutError("Synthesis timed out")
            if errors:
                raise RuntimeError(errors[0])
            successful = True
        finally:
            if successful:
                pool.return_synthesizer(synthesizer)
            else:
                synthesizer.close()

try:
    with ThreadPoolExecutor(max_workers=3) as executor:
        list(executor.map(synthesize, range(3)))
finally:
    pool.shutdown()

Sambert

This example shares one object pool across three concurrent one-way streaming synthesis tasks and saves audio to sambert_0.mp3, sambert_1.mp3, and sambert_2.mp3.

import com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.utils.Constants;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.io.FileOutputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;

public class PooledSambert {
    static class Factory extends BasePooledObjectFactory<SpeechSynthesizer> {
        @Override
        public SpeechSynthesizer create() { return new SpeechSynthesizer(); }

        @Override
        public PooledObject<SpeechSynthesizer> wrap(SpeechSynthesizer value) {
            return new DefaultPooledObject<>(value);
        }

        @Override
        public void destroyObject(PooledObject<SpeechSynthesizer> value) {
            value.getObject().getSyncApi().close(1000, "done");
        }
    }

    static void synthesize(GenericObjectPool<SpeechSynthesizer> pool, int index, String text)
            throws Exception {
        SpeechSynthesizer synthesizer = pool.borrowObject();
        boolean successful = false;
        CountDownLatch finished = new CountDownLatch(1);
        AtomicReference<Exception> error = new AtomicReference<>();
        try (FileOutputStream audio = new FileOutputStream("sambert_" + index + ".mp3")) {
            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("sambert-zhichu-v1")
                .text(text)
                .format(SpeechSynthesisAudioFormat.MP3)
                .enablePhonemeTimestamp(true)
                .enableWordTimestamp(true)
                .build();
            synthesizer.call(param, new ResultCallback<SpeechSynthesisResult>() {
                @Override
                public void onEvent(SpeechSynthesisResult result) {
                    if (result.getAudioFrame() != null) {
                        byte[] bytes = result.getAudioFrame().array();
                        try { audio.write(bytes); }
                        catch (Exception e) { error.compareAndSet(null, e); }
                    }
                }

                @Override
                public void onComplete() { finished.countDown(); }

                @Override
                public void onError(Exception e) {
                    error.compareAndSet(null, e);
                    finished.countDown();
                }
            });
            if (!finished.await(60, TimeUnit.SECONDS)) {
                throw new TimeoutException("Synthesis timed out");
            }
            if (error.get() != null) { throw error.get(); }
            successful = true;
        } finally {
            if (successful) { pool.returnObject(synthesizer); }
            else { pool.invalidateObject(synthesizer); }
        }
    }

    public static void main(String[] args) throws Exception {
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference";
        int poolSize = Integer.parseInt(System.getenv().getOrDefault("SAMBERT_OBJECTPOOL_SIZE", "500"));
        GenericObjectPoolConfig<SpeechSynthesizer> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(poolSize);
        config.setMaxIdle(poolSize);
        config.setMaxWait(Duration.ofSeconds(60));
        ExecutorService executor = Executors.newFixedThreadPool(3);
        try (GenericObjectPool<SpeechSynthesizer> pool = new GenericObjectPool<>(new Factory(), config)) {
            String[] texts = {"Moonlight shines in front of my bed.", "I look up at the bright moon.", "Hello, welcome to Alibaba Cloud Model Studio."};
            List<Future<?>> futures = new ArrayList<>();
            for (int i = 0; i < texts.length; i++) {
                final int index = i;
                futures.add(executor.submit(() -> {
                    try { synthesize(pool, index, texts[index]); }
                    catch (Exception e) { throw new RuntimeException(e); }
                }));
            }
            Exception failure = null;
            for (Future<?> future : futures) {
                try { future.get(); }
                catch (ExecutionException e) { failure = e; }
            }
            if (failure != null) { throw failure; }
        } finally {
            executor.shutdownNow();
        }
    }
}

Performance evaluation and diagnostics

Connection warm-up at startup and recovery

The Python pool establishes connections during initialization. Java GenericObjectPool creates objects on demand and connects on the first synthesis call, so warming up Java connections requires actual synthesis requests.

After startup or network recovery, run warm-up calls and increase concurrency gradually. Before performance testing, warm up at the target concurrency, for example for 1–2 minutes, and collect measurements once connections are being reused steadily. Increasing concurrency gradually avoids blocking caused by establishing many WebSocket connections at once.

Latency and real-time factor evaluation

The first call includes WebSocket connection overhead. Measure its first-audio latency and total task time separately from calls that reuse a connection. You can also use the real-time factor (RTF, total synthesis time / audio duration) to evaluate synthesis speed.

SDK-side first-audio latency includes connection establishment and network transmission, so it is not a measure of model inference time alone. For Qwen-Audio-TTS/CosyVoice, a Python object provides get_first_package_delay() for first-audio latency and get_last_request_id() for the request ID used to correlate request logs. Java objects provide getLastRequestId() for the request ID.

Object pool waits and timeouts

At maxTotal, borrowing from a Java object pool waits for an available object. Check pool capacity, object returns, and connection cleanup to avoid extra time spent waiting for objects.

Request spikes and rate limits

Mass reconnection after startup, network interruptions, or many server errors can cause tasks to accumulate. When connections recover, simultaneous submission of those tasks can create a spike and trigger account limits.

Check for network problems or many server errors before the spike, such as Requests rate limit exceeded, please try again later.. Control concurrency during startup and recovery. In Java, maxTotal limits the number of objects borrowed simultaneously from the same pool.

Check account quotas. To request an increase, follow the procedure in Rate limits. Adjust server specifications or add servers for the actual workload.

Network bandwidth and server load

Check whether network bandwidth is saturated or concurrency is too high. Adjust concurrency or server capacity for the workload.