Real-time speech synthesis Java SDK
This guide shows Java developers how to use the ConvAI Voice SDK for real-time speech synthesis, covering streaming text input, receiving streaming audio, saving audio files, real-time PCM playback, word-level timestamps, and task cancellation.
Applies to:
JDK: 8 or later
SDK:
com.aliyun.convai:convai-voice-sdk:0.1.0 (Use the latest version)protocol: WebSocket (The SDK handles protocol frame assembly internally.)
1. Prerequisites
Before you begin, obtain the following:
An API key from Voice Studio, in the format
sk-xxxxxxxx. You can obtain an API key from the console. For more information, see Create an API key.A platform voice ID, the
voiceVersionIdreturned byListConsumableVoices. You can obtain a voice ID from the console. For more information, see Voice ID.
1.1 Service endpoint
wss://convai-platform.aliyuncs.com/api-ws/v1/inference
1.2 Maven dependency
In pom.xml, add the following:
<dependency>
<groupId>com.aliyun.convai</groupId>
<artifactId>convai-voice-sdk</artifactId>
<version>0.1.0</version>
</dependency>
<!-- Optional: The SDK uses slf4j-api. Your application can choose a logging implementation. -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.6</version>
<scope>runtime</scope>
</dependency>2. SDK core objects
Object | Description | Recommended lifecycle |
| Manages authentication, WebSocket connections, the connection pool, heartbeats, and reconnection. | This is a heavy object. Create a single instance per application process and reuse it globally. |
| Specifies the parameters for a synthesis task, such as the voice, format, and sample rate. | You can reuse an instance for each synthesis configuration. |
| Represents a streaming synthesis session. | Create a new instance for each session. You must make calls from a single producer thread. |
| Receives audio clips, sentence-level events, and task events. | Within the callback, perform only quick operations such as disk writes or queuing. |
| Represents the final result of a synthesis task, containing the number of billing characters, first packet latency, and trace ID. | Returned by |
Recommended call flow:
Create a global VoiceRealtimeClient
↓
Create a SynthesisSession for the current synthesis task
↓
Call write(text) repeatedly; the SDK streams audio back
↓
Call finish() to wait for all trailing audio to be sent
↓
Close the session
↓
Close the client when the application exits3. Quick start: Synthesize short text to WAV
The following example uses the synthesize() method to send short text in a single request, wait for the complete audio, and save the result as a playable WAV file.
import com.convai.voice.sdk.AudioFormat;
import com.convai.voice.sdk.SynthesisAudio;
import com.convai.voice.sdk.SynthesisOptions;
import com.convai.voice.sdk.realtime.VoiceRealtimeClient;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ShortTextWavExample {
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("CONVAI_API_KEY");
String voiceId = System.getenv("CONVAI_VOICE_ID");
VoiceRealtimeClient client = VoiceRealtimeClient.builder()
.endpoint("wss://convai-platform.aliyuncs.com/api-ws/v1/inference")
.apiKey(apiKey)
.build();
try {
SynthesisOptions options = SynthesisOptions.builder()
.voice(voiceId)
.format(AudioFormat.WAV)
.sampleRate(22050)
.build();
SynthesisAudio result = client.synthesize(
options, "Hello, welcome to the real-time speech synthesis service.");
Files.write(Paths.get("output.wav"), result.audio());
System.out.println("Audio bytes=" + result.size());
System.out.println("Billable characters=" + result.result().characters());
System.out.println("First packet delay=" + result.result().firstPackageDelayMillis() + " ms");
System.out.println("requestUuid=" + result.result().lastRequestUuid());
} finally {
client.close();
}
}
}Before you begin:
export CONVAI_API_KEY="sk-your-voice-studio-api-key"
export CONVAI_VOICE_ID="your-voice-id"
mvn -q compile org.codehaus.mojo:exec-maven-plugin:3.1.0:java \
-Dexec.mainClass=ShortTextWavExample4. Parameter list
4.1 VoiceRealtimeClient.Builder client parameters
Builder method | Required | Default | Description |
| Yes | None | The WebSocket service address for real-time speech synthesis. |
| One of the two | None | A fixed API key. Do not hard-code it in your application or commit it to a code repository. |
| One of the two | None | Suitable for configuration centers or temporary credentials. The provider can refresh the credential if authentication fails. |
| No |
| Enables text normalization (TN). This is a handshake-level configuration shared by all sessions of the same client. |
| No |
| Set the application name and version to facilitate server-side troubleshooting. |
| No | None | Adds a custom handshake request header. Do not override authentication headers or headers reserved by the platform. |
| No |
| The WebSocket connection timeout, in milliseconds. |
| No |
| The timeout for waiting for a task start confirmation, in milliseconds. |
| No |
| The maximum time for |
| No |
| Guards for idle connections, task stalls, and heartbeats. Keep the default settings in a production environment. |
| No |
| The retry backoff policy for connection failures and concurrency limit exceeded errors. |
| No |
| The strategy for handling network interruptions. For more information, see Section 10. |
Default guard settings:
WebSocket heartbeat: 20 seconds.
Idle connection timeout: 45 seconds.
Streaming text stall guard: 18 seconds. The SDK gracefully closes the current task before the server-side timeout.
Maximum connection attempts: 5, with random/exponential backoff.
4.2 SynthesisOptions.Builder synthesis parameters
Builder method | Required | Default | Description |
| Yes | None | The platform voice ID ( |
| No |
|
|
| No |
|
|
| No |
| The valid range is |
| No |
| The speech rate. The valid range is |
| No |
| The pitch. The valid range is |
| No | Engine default | The valid range is |
| No | None | The valid range is |
| No | Empty | Language hints, such as |
| No | None | Instructions for dialect, emotion, or role, with a maximum length of 2,000 characters. Feature support depends on the model bound to the voice. |
| No |
| If enabled, you can call |
| No |
| Returns word-level timestamps in the end-of-sentence event. This parameter cannot be used with |
| No | None | Custom pronunciations and text replacements. Feature support depends on the model bound to the voice. |
| No |
| Filters out Markdown syntax before synthesis. Feature support depends on the model. |
| No |
| Embeds an AIGC tag in the audio. |
| No | None | Requires |
| No | None | Requires a propagator to be set. This parameter identifies the propagation behavior. |
| No | None | Passes through new parameters that are not yet modeled by the SDK. Do not override fields managed by the SDK. |
| No | None | Sets multiple additional parameters at once. |
The SDK does not provide a model parameter. The platform automatically determines the model based on the voice ID's binding relationship. You do not need to specify the model name.
The default format for the SDK isMP3. All file-saving examples in this document explicitly set the format toAudioFormat.WAVand therefore will not generate MP3 files.
4.3 Audio formats
Format | Features | Scenarios |
MP3 | Small file size and high compatibility. Audio clips can be concatenated and saved to disk. | General file saving and network transmission. |
PCM | Lowest latency. 16-bit, little-endian, mono, no file header. | Real-time playback, telephony, or RTC audio pipelines. |
WAV | Includes a file header, making it easy to play directly. | Playback after receiving the full audio stream, testing, and acceptance. |
OPUS | High compression ratio. | Bandwidth-constrained scenarios. |
For PCM, the length of downstream audio fragments is not fixed. Do not assume that each WebSocket audio fragment is a fixed 20 ms. Instead, treat the data as a continuous byte stream and write it to the playback buffer in the order it is received.
5. SDK methods
5.1 VoiceRealtimeClient
Method | Description |
| Creates a streaming session. The connection is established lazily on the first |
| A convenience method for short text. This is a blocking call that returns the complete audio. |
| Closes all sessions, the connection pool, and background threads. Call this when the application exits. |
5.2 SynthesisSession
Method | Description |
| Establishes the connection and starts the task early for fail-fast behavior. You usually do not need to call this method. |
| Sends text incrementally. This method can be called multiple times. |
| Sends text. If the second parameter is |
| Forces synthesis of the current trailing sentence fragment in the cache. This feature is mutually exclusive with word-level timestamps. |
| Ends the session gracefully and blocks until all audio is received. Returns a |
| Stops subsequent audio and ends the session. Use this method to handle user interruptions. |
| If the session has not ended, this method attempts to cancel it and release all associated resources. |
Text limits: A single write() call cannot exceed 20,000 characters. The cumulative number of characters for a single upstream task cannot exceed 200,000. For long Chinese text, split the input into complete sentences and include the punctuation at the end of each.
6. Scenario 2: Synthesize streaming text to a WAV file
import com.convai.voice.sdk.*;
import com.convai.voice.sdk.realtime.*;
import java.io.*;
import java.util.concurrent.atomic.AtomicReference;
public class LlmStreamingWavExample {
public static void main(String[] args) throws Exception {
VoiceRealtimeClient client = VoiceRealtimeClient.builder()
.endpoint("wss://convai-platform.aliyuncs.com/api-ws/v1/inference")
.apiKey(System.getenv("CONVAI_API_KEY"))
.finishTimeoutMillis(10 * 60 * 1000L)
.build();
SynthesisOptions options = SynthesisOptions.builder()
.voice(System.getenv("CONVAI_VOICE_ID"))
.format(AudioFormat.WAV)
.sampleRate(22050)
.build();
final AtomicReference<IOException> writeError = new AtomicReference<IOException>();
try (final OutputStream out = new BufferedOutputStream(new FileOutputStream("stream.wav"))) {
SynthesisListener listener = new SynthesisListener() {
public void onAudio(byte[] audio) {
try {
out.write(audio);
} catch (IOException e) {
writeError.compareAndSet(null, e);
}
}
public void onSentence(SentenceEvent event) {
if (event.type() == SentenceEvent.Type.SENTENCE_END) {
System.out.println("Synthesized: " + event.originalText());
}
}
};
try (SynthesisSession session = client.newSession(options, listener)) {
// In a real-world scenario, these strings can come directly from the streaming output of a large language model.
session.write("The weather is great today, ");
session.write("perfect for a walk. ");
session.write("Remember to bring a water bottle.");
SynthesisResult result = session.finish();
out.flush();
if (writeError.get() != null) throw writeError.get();
System.out.println("billable characters=" + result.characters());
System.out.println("requestUuid=" + result.lastRequestUuid());
}
} finally {
client.close();
}
}
}Notes:
The
onAudiocallback runs on the WebSocket read thread. Inside the callback, perform only fast operations such as writing to disk or enqueuing data.Inside
onAudio, do not callwrite(),flush(),finish(), or make a network request.Send text as complete sentences whenever possible. Call
flush()to synthesize sentence fragments that lack end-of-sentence punctuation.
7. Use case 3: Synthesize, play, and save PCM
This example uses the Java Sound API (included with JDK 8) to play PCM audio while saving the raw PCM data. After synthesis completes, the example adds a WAV header to create a playable output.wav file. The PCM parameters must match those in the request: 16-bit, little-endian, mono, and a 24000 Hz sample rate.
import com.convai.voice.sdk.AudioFormat;
import com.convai.voice.sdk.SynthesisOptions;
import com.convai.voice.sdk.SynthesisResult;
import com.convai.voice.sdk.realtime.SynthesisListener;
import com.convai.voice.sdk.realtime.SynthesisSession;
import com.convai.voice.sdk.realtime.VoiceRealtimeClient;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class PcmStreamingPlaybackExample {
private static final byte[] END = new byte[0];
public static void main(String[] args) throws Exception {
final int sampleRate = 24000;
final BlockingQueue<byte[]> queue = new LinkedBlockingQueue<byte[]>();
javax.sound.sampled.AudioFormat javaSoundFormat =
new javax.sound.sampled.AudioFormat(sampleRate, 16, 1, true, false);
final SourceDataLine speaker = (SourceDataLine) AudioSystem.getLine(
new DataLine.Info(SourceDataLine.class, javaSoundFormat));
speaker.open(javaSoundFormat);
speaker.start();
final OutputStream recording = new BufferedOutputStream(
new FileOutputStream("output.pcm"));
Thread consumer = new Thread(new Runnable() {
public void run() {
try {
while (true) {
byte[] pcm = queue.take();
if (pcm == END) break;
recording.write(pcm);
speaker.write(pcm, 0, pcm.length);
}
recording.flush();
speaker.drain();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try { recording.close(); } catch (IOException ignored) { }
speaker.stop();
speaker.close();
}
}
}, "pcm-playback");
consumer.start();
VoiceRealtimeClient client = VoiceRealtimeClient.builder()
.endpoint("wss://convai-platform.aliyuncs.com/api-ws/v1/inference")
.apiKey(System.getenv("CONVAI_API_KEY"))
.build();
SynthesisOptions options = SynthesisOptions.builder()
.voice(System.getenv("CONVAI_VOICE_ID"))
.format(AudioFormat.PCM)
.sampleRate(sampleRate)
.build();
try {
SynthesisListener listener = new SynthesisListener() {
public void onAudio(byte[] pcm) {
queue.offer(pcm); // The callback only enqueues to avoid blocking the WS read thread on speaker writes.
}
};
try (SynthesisSession session = client.newSession(options, listener)) {
session.write("Hello. You are now synthesizing and playing PCM audio at the same time.");
session.write("The full audio is also saved to a local file.");
SynthesisResult result = session.finish();
System.out.println("requestUuid=" + result.lastRequestUuid());
}
} finally {
client.close();
queue.offer(END);
consumer.join();
}
pcmToWav("output.pcm", "output.wav", sampleRate);
System.out.println("WAV recording saved to: " + Paths.get("output.wav").toAbsolutePath());
}
private static void pcmToWav(String pcmPath, String wavPath, int sampleRate)
throws Exception {
byte[] pcm = Files.readAllBytes(Paths.get(pcmPath));
ByteBuffer header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN);
header.put("RIFF".getBytes("US-ASCII"));
header.putInt(36 + pcm.length);
header.put("WAVEfmt ".getBytes("US-ASCII"));
header.putInt(16).putShort((short) 1).putShort((short) 1);
header.putInt(sampleRate).putInt(sampleRate * 2);
header.putShort((short) 2).putShort((short) 16);
header.put("data".getBytes("US-ASCII")).putInt(pcm.length);
try (OutputStream out = Files.newOutputStream(Paths.get(wavPath))) {
out.write(header.array());
out.write(pcm);
}
}
}Validate raw PCM playback:
ffplay -f s16le -ar 24000 -ac 1 output.pcmAfter the example finishes, it generates a playable output.wav file. When processing very long audio files in a production environment, use RandomAccessFile to write PCM data as it arrives. You can then seek back to the beginning and write the correct length into the WAV header when you close the file. This approach avoids loading the entire PCM content into memory.
Production playback recommendations:
Use a dedicated playback thread and a bounded jitter buffer. Do not play audio directly in the SDK callback thread.
On a buffer underrun, output silence or comfort noise. Do not loop the last voiced frame.
Do not infer audio duration from the size of each WebSocket frame. PCM duration is
total bytes / 2 / sample rate.
8. Use case 4: Text normalization and word timestamps
Text normalization (TN) is a client-level configuration, while word timestamps are a session parameter. When text normalization is enabled, timestamp offsets correspond to the normalized text.
import com.convai.voice.sdk.*;
import com.convai.voice.sdk.realtime.*;
import java.io.*;
public class WordTimestampExample {
public static void main(String[] args) throws Exception {
VoiceRealtimeClient client = VoiceRealtimeClient.builder()
.endpoint("wss://convai-platform.aliyuncs.com/api-ws/v1/inference")
.apiKey(System.getenv("CONVAI_API_KEY"))
.textNormalization(true)
.build();
SynthesisOptions options = SynthesisOptions.builder()
.voice(System.getenv("CONVAI_VOICE_ID"))
.format(AudioFormat.WAV)
.sampleRate(22050)
.wordTimestampEnabled(true)
.build();
try (final OutputStream out = new FileOutputStream("timestamp.wav")) {
SynthesisListener listener = new SynthesisListener() {
public void onAudio(byte[] audio) {
try { out.write(audio); } catch (IOException e) { throw new RuntimeException(e); }
}
public void onSentence(SentenceEvent event) {
if (event.type() != SentenceEvent.Type.SENTENCE_END) return;
System.out.println("Sentence: " + event.originalText());
for (Word word : event.words()) {
System.out.printf("%s: %d-%d ms%n",
word.text(), word.beginTime(), word.endTime());
}
}
};
try (SynthesisSession session = client.newSession(options, listener)) {
session.write("Today is September 24, 2026, and the order amount is 128.5 yuan.");
session.finish();
}
} finally {
client.close();
}
}
}You cannot call flush() or write(text, true) when word timestamps are enabled. Additionally, you cannot enable SSML and word timestamps at the same time.
9. Scenario 5: Cancel on user interruption
When a user starts speaking, switches pages, or actively stops playback, you should call cancel(). Do not directly disconnect the underlying WebSocket.
import com.convai.voice.sdk.*;
import com.convai.voice.sdk.realtime.*;
public class CancelSynthesisExample {
public static void main(String[] args) throws Exception {
VoiceRealtimeClient client = VoiceRealtimeClient.builder()
.endpoint("wss://convai-platform.aliyuncs.com/api-ws/v1/inference")
.apiKey(System.getenv("CONVAI_API_KEY"))
.build();
SynthesisOptions options = SynthesisOptions.builder()
.voice(System.getenv("CONVAI_VOICE_ID"))
.format(AudioFormat.PCM)
.sampleRate(24000)
.build();
try {
SynthesisListener listener = new SynthesisListener() {
public void onAudio(byte[] audio) {
// In a real-world application, add the audio to a player queue.
System.out.println("Received PCM: " + audio.length + " bytes");
}
};
try (SynthesisSession session = client.newSession(options, listener)) {
session.write("This is a long text to demonstrate a user interruption. "
+ "When the user starts speaking, the client should immediately cancel the remaining synthesis.");
Thread.sleep(500); // Simulate a user interruption during playback.
SynthesisResult result = session.cancel();
System.out.println("Canceled, cancelled=" + result.cancelled());
}
} finally {
client.close();
}
}
}Cancellation discards any unsynthesized cached text and stops further audio output. You cannot recall audio that has already been sent to the client. Note that you are still charged for any text synthesized before the cancellation.
Error handling and retries
All exceptions thrown by the SDK inherit from VoiceSdkException and are unchecked exceptions.
Exception | Description | Recommended action |
| Local parameter validation failed. | Fix the parameters. Do not retry. |
| The API key is invalid, has expired, or does not grant permission for the specified voice. | Refresh the credential or check your permissions for the voice. |
| The request exceeded the concurrent connections limit and failed despite the SDK's backoff attempts. | Reduce concurrency or retry later. |
| The server-side task failed. | Check the error code to decide whether to retry. |
| The synthesis task was interrupted by a network error. | Use the returned boundaries to decide whether to resend the unspoken text. |
| A connection, send, or wait timeout occurred. | Check your network connection and retry a limited number of times. |
Recommended error handling:
try {
SynthesisResult result = session.finish();
} catch (com.convai.voice.sdk.error.TaskFailedException e) {
System.err.println("errorCode=" + e.rawErrorCode());
System.err.println("taskId=" + e.taskId());
System.err.println("requestUuid=" + e.requestUuid());
System.err.println("sessionId=" + e.sessionId());
if (e.errorCode().retryable()) {
// Implement a retry mechanism with a limit and backoff in your application.
}
} catch (com.convai.voice.sdk.error.TaskInterruptedException e) {
System.err.println("Spoken Sentences=" + e.spokenSentences());
System.err.println("Unspoken Text=" + e.unspokenText());
}The Spoken Sentences count indicates that the SDK has received the completion events for the corresponding sentences, not that the audio has finished playing through the speaker. In real-time playback scenarios, wait for the playback queue to empty, then call SourceDataLine.drain() to confirm that audio playback is complete.
ResumePolicy:
FAIL_FAST(Default): When a network error occurs, this policy throws aTaskInterruptedException. Your application then decides whether to retry the task.RESUME_UNSPOKEN: The SDK automatically resends any text not yet confirmed as spoken. This may result in minor repetitions, omissions, or changes in prosody. If text normalization (TN) is enabled, boundary estimation may also drift. This policy is suitable only for scenarios where continuity is prioritized over a consistent listening experience.
Results and observability
SynthesisResult provides the following:
Method | Description |
| The total number of billable characters for the session. |
| Results for each segment that the SDK automatically generates. |
| Indicates whether the session was canceled. |
| The latency (in milliseconds) between sending the first text frame and receiving the first audio frame for the first segment. |
| The server-side trace ID for the last segment. This ID is required for troubleshooting. |
Each Segment object provides the following methods: taskId(), requestUuid(), sessionId(), characters(), autoSegmented(), and firstPackageDelayMillis().
To prevent timeouts caused by text stalls within a task, the SDK may automatically split a single business session into multiple upstream tasks. As a result:
segments().size()can be greater than 1. This is expected behavior.For each task, the sentence
indexrestarts from 0. UseSentenceEvent.taskId()to distinguish between sentences across different tasks.For troubleshooting, submit the
taskId,requestUuid, andsessionIdfor all segments.
12. Connection and concurrency best practices
Create only one
VoiceRealtimeClientinstance per application process. Do not create a new instance for each synthesis task.Create a new
SynthesisSessionfor each conversation. Do not call the same session concurrently from different threads.Call
finish()to complete a session. Callcancel()to handle a user interruption.Wait for
finish()to return before closing the recording file; otherwise, the tail-end audio will be lost.Use the callback thread only for quick operations, such as disk writes or enqueuing data. Offload time-consuming tasks such as playback, transcoding, and uploads to a separate thread.
Each concurrent session consumes your concurrent connection quota. If you receive a concurrency limit exceeded error, avoid frequent reconnection attempts.
A heartbeat only maintains the network link and does not guarantee that the session will remain active indefinitely. The SDK automatically manages the connection lifecycle.
Do not hard-code your API key in a client installation package, browser code, logs, or code repository. Instead, inject the key through server-side configuration or a key management system.
13. FAQ
13.1 No immediate audio
The engine typically synthesizes audio one sentence at a time. To trigger synthesis, include end-of-sentence punctuation or call flush() when appropriate. Avoid calling flush() too frequently, such as for every token, as this can make the speech sound fragmented.
13.2 Missing audio ending
You must call finish() and wait for it to return. You may still receive audio chunks before finish() returns.
13.3 Voice name not found
The SDK's voice() method accepts only a platform voice ID, which corresponds to the voiceVersionId. It does not accept a vendor voice name.
13.4 PCM playback issues
Ensure that your player's parameters exactly match those in your request:
16-bit signed PCM
Little-endian
Mono
The sample rate must match the value from
sampleRate().
Do not play the PCM audio as 8-bit, big-endian, stereo, or with an incorrect sample rate.
13.5 Why do I receive multiple taskIds?
If the LLM output stalls for too long, the SDK automatically closes the current task gracefully before the server side timeout occurs. The next write() call automatically creates a new task. The business session remains the same, and the final results are aggregated through segments().
13.6 Information for reporting issues
Please provide the following:
The exact time the issue occurred.
The
requestUuid,taskId, andsessionId.The SDK version and JDK version.
The audio format, sample rate, and voice ID.
The full exception type, error code, and error message.
For audio-related issues, provide the original persisted file from the SDK, not a recording that has been transcoded by a player, RTC, or a telephony system.