Java SDK
Use the Java SDK to submit text in a single request and receive synthesized speech as an audio stream. SSML input is supported.
Prerequisites
Activate the commercial edition of the CosyVoice service. For service requirements, see Long-text-to-speech API.
Obtain a project Appkey. For more information, see Manage projects.
Obtain an NLS token for authentication. For more information, see Obtain a token using an SDK.
Install the SDK
The examples use Java SDK 2.2.19. Add the following Maven dependencies. This text input mode requires SDK 2.2.18 or later.
<dependencies>
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-common</artifactId>
<version>2.2.19</version>
</dependency>
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-tts</artifactId>
<version>2.2.19</version>
</dependency>
</dependencies>
The Java SDK depends on Netty. If the application also depends on Netty, use version 4.1.17.Final or later and resolve dependency conflicts.
Usage notes
NlsClientcan be reused across synthesis tasks. We recommend creating it when the application starts and callingshutdown()when the application exits.Create a separate
StreamInputTtsandStreamInputTtsListenerfor each task. A task object cannot be reused, and a listener must not be shared across task objects.Configure the Appkey, voice, audio format, and other request parameters before starting synthesis.
After the task finishes or fails, call
StreamInputTts.close()to release the connection.
For supported voices, audio formats, and service limits, see Long-text-to-speech API.
Code examples
Set the project Appkey and NLS token in the NLS_APPKEY and NLS_TOKEN environment variables. Choose an example based on how the audio will be used.
Save audio
The example saves 24 kHz, 16-bit, mono PCM audio to output.pcm.
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.tts.StreamInputTts;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsListener;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsResponse;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class SaveAudioDemo {
public static void main(String[] args) throws Exception {
String appkey = Objects.requireNonNull(System.getenv("NLS_APPKEY"), "Set NLS_APPKEY");
String token = Objects.requireNonNull(System.getenv("NLS_TOKEN"), "Set NLS_TOKEN");
AtomicBoolean completed = new AtomicBoolean(false);
AtomicReference<Exception> failure = new AtomicReference<>();
try (OutputStream audio = Files.newOutputStream(Paths.get("output.pcm"))) {
NlsClient client = new NlsClient(
"wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1", token);
StreamInputTts tts = null;
try {
StreamInputTtsListener listener = new StreamInputTtsListener() {
@Override
public void onSynthesisStart(StreamInputTtsResponse response) {}
@Override
public void onSentenceBegin(StreamInputTtsResponse response) {}
@Override
public void onSentenceEnd(StreamInputTtsResponse response) {}
@Override
public void onSentenceSynthesis(StreamInputTtsResponse response) {}
@Override
public void onAudioData(ByteBuffer buffer) {
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
try {
audio.write(data);
} catch (Exception e) {
failure.compareAndSet(null, e);
}
}
@Override
public void onSynthesisComplete(StreamInputTtsResponse response) {
completed.set(true);
System.out.println("Synthesis completed. taskId=" + response.getTaskId());
}
@Override
public void onFail(StreamInputTtsResponse response) {
failure.compareAndSet(null, new IllegalStateException(
"taskId=" + response.getTaskId() + ", status=" + response.getStatus()
+ ", message=" + response.getStatusText()));
}
};
tts = new StreamInputTts(client, listener);
tts.setAppKey(appkey);
tts.setVoice("longxiaochun_v2");
tts.setFormat(OutputFormatEnum.PCM);
tts.setSampleRate(24000);
tts.startTts("<speak>Hello. Welcome to speech synthesis.</speak>", 10000);
tts.waitForComplete();
if (failure.get() != null) {
throw failure.get();
}
if (!completed.get()) {
throw new IllegalStateException("Connection closed before synthesis completed");
}
System.out.println("Audio saved to output.pcm");
} finally {
try {
if (tts != null) {
tts.close();
}
} finally {
client.shutdown();
}
}
}
}
}
Play audio in real time
The runtime must have an available audio output device. The example plays 24 kHz, 16-bit, mono, signed little-endian PCM audio.
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.tts.StreamInputTts;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsListener;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsResponse;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
public class PlayAudioDemo {
public static void main(String[] args) throws Exception {
String appkey = Objects.requireNonNull(System.getenv("NLS_APPKEY"), "Set NLS_APPKEY");
String token = Objects.requireNonNull(System.getenv("NLS_TOKEN"), "Set NLS_TOKEN");
AtomicBoolean completed = new AtomicBoolean(false);
AtomicReference<Exception> failure = new AtomicReference<>();
try (Player player = new Player(failure)) {
NlsClient client = new NlsClient(
"wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1", token);
StreamInputTts tts = null;
try {
StreamInputTtsListener listener = new StreamInputTtsListener() {
@Override
public void onSynthesisStart(StreamInputTtsResponse response) {}
@Override
public void onSentenceBegin(StreamInputTtsResponse response) {}
@Override
public void onSentenceEnd(StreamInputTtsResponse response) {}
@Override
public void onSentenceSynthesis(StreamInputTtsResponse response) {}
@Override
public void onAudioData(ByteBuffer buffer) {
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
player.write(data);
}
@Override
public void onSynthesisComplete(StreamInputTtsResponse response) {
completed.set(true);
System.out.println("Synthesis completed. taskId=" + response.getTaskId());
}
@Override
public void onFail(StreamInputTtsResponse response) {
failure.compareAndSet(null, new IllegalStateException(
"taskId=" + response.getTaskId() + ", status=" + response.getStatus()
+ ", message=" + response.getStatusText()));
}
};
tts = new StreamInputTts(client, listener);
tts.setAppKey(appkey);
tts.setVoice("longxiaochun_v2");
tts.setFormat(OutputFormatEnum.PCM);
tts.setSampleRate(24000);
tts.startTts("<speak>Hello. Welcome to speech synthesis.</speak>", 10000);
tts.waitForComplete();
if (failure.get() != null) {
throw failure.get();
}
if (!completed.get()) {
throw new IllegalStateException("Connection closed before synthesis completed");
}
player.finish();
if (failure.get() != null) {
throw failure.get();
}
} finally {
try {
if (tts != null) {
tts.close();
}
} finally {
client.shutdown();
}
}
}
}
private static final class Player implements AutoCloseable {
private static final byte[] END = new byte[0];
private final BlockingQueue<byte[]> queue = new LinkedBlockingQueue<>();
private final SourceDataLine line;
private final Thread thread;
Player(AtomicReference<Exception> failure) throws Exception {
AudioFormat format = new AudioFormat(24000, 16, 1, true, false);
line = AudioSystem.getSourceDataLine(format);
try {
line.open(format);
line.start();
} catch (Exception e) {
line.close();
throw e;
}
thread = new Thread(() -> {
try {
while (true) {
byte[] data = queue.take();
if (data == END) {
break;
}
int offset = 0;
while (offset < data.length && !Thread.currentThread().isInterrupted()) {
int written = line.write(data, offset, data.length - offset);
if (written <= 0) {
throw new IllegalStateException("Audio output stopped");
}
offset += written;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
failure.compareAndSet(null, e);
}
}, "audio-player");
thread.start();
}
void write(byte[] data) {
queue.add(data);
}
void finish() throws InterruptedException {
queue.add(END);
thread.join();
line.drain();
}
@Override
public void close() throws InterruptedException {
thread.interrupt();
line.stop();
line.flush();
line.close();
thread.join();
}
}
}
SDK reference
Task methods
Create a task with new StreamInputTts(NlsClient client, StreamInputTtsListener listener). To specify a token for an individual task, use new StreamInputTts(NlsClient client, String token, StreamInputTtsListener listener).
|
Method |
Parameters |
Description |
|
|
|
Starts synthesis and sends the complete text once. |
|
|
— |
Sends the end-of-input notification and blocks while waiting for completion. Call |
|
|
— |
Closes the connection for the task. |
Request settings
|
Method |
Type |
Description |
|
|
|
Sets the project Appkey. |
|
|
|
Sets the voice name. |
|
|
|
Sets the audio encoding format. The default is PCM. |
|
|
|
Sets the sample rate in Hz. The SDK default is 24000. |
|
|
|
Sets the bitrate in kbit/s for OPUS audio. |
|
|
|
Sets the volume from 0 to 100. The default is 50. |
|
|
|
Sets the speech rate from -500 to 500. The default is 0. |
|
|
|
Sets the pitch from -500 to 500. The default is 0. |
|
|
|
Adds a custom request parameter, such as an AIGC metadata parameter. |
Callbacks
Implement the callbacks in StreamInputTtsListener. Event callbacks receive StreamInputTtsResponse; the audio callback receives ByteBuffer. Timestamp availability depends on the selected voice and request settings. For details, see Long-text-to-speech API.
|
Callback |
Description |
|
|
The server is ready to synthesize speech. |
|
|
A sentence starts. |
|
|
Receives incremental timestamp information. |
|
|
A sentence ends, with sentence timestamps. |
|
|
The synthesis task is complete. |
|
|
The task fails. Read the task ID, status code, and error message from the response. |
|
|
Receives a chunk of binary audio data. |
Optional settings
The following snippets use the tts object from the code examples. Apply request settings before starting the task.
Use the OPUS and AIGC snippets with the Save audio example, and change the output file extension to match the format. The real-time playback example uses PCM audio.
OPUS encoding
Before starting synthesis, set the format to OPUS and configure the bitrate as needed:
tts.setFormat(OutputFormatEnum.OPUS);
tts.setBitRate(64);
Invisible AIGC metadata
To add invisible AIGC metadata, configure the following parameters with addCustomedParam before starting synthesis:
|
Parameter |
Type |
Description |
|
|
Boolean |
Adds invisible AIGC metadata to WAV, MP3, or OPUS audio. The default is |
|
|
String |
Sets |
|
|
String |
Sets |
tts.setFormat(OutputFormatEnum.WAV);
tts.addCustomedParam("enable_aigc_tag", true);
tts.addCustomedParam("aigc_propagator", "example-propagator");
tts.addCustomedParam("aigc_propagate_id", "example-propagation-id");
SSML input
Select a voice that supports SSML. For voice support and SSML usage, see Long-text-to-speech API.
startTts enables SSML. Pass the complete SSML text to this method:
tts.startTts("<speak bgm=\"http://nls.alicdn.com/bgm/2.wav\">How is the weather today?</speak>", 10000);
tts.waitForComplete();
Error handling
Handle task failures in onFail and retain response.getTaskId(), response.getStatus(), and response.getStatusText() for troubleshooting. For server status codes and solutions, see Error code reference.