Java SDK

Updated at:

Use the Java SDK to submit text in a single request and receive synthesized speech as an audio stream. SSML input is supported.

Prerequisites

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

  • NlsClient can be reused across synthesis tasks. We recommend creating it when the application starts and calling shutdown() when the application exits.

  • Create a separate StreamInputTts and StreamInputTtsListener for 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

startTts(String text) / startTts(String text, long milliSeconds)

String text, long milliSeconds

Starts synthesis and sends the complete text once. milliSeconds is the start confirmation timeout in milliseconds.

waitForComplete()

—

Sends the end-of-input notification and blocks while waiting for completion. Call close() afterward to release the connection.

close()

—

Closes the connection for the task.

Request settings

Method

Type

Description

setAppKey(String appKey)

String

Sets the project Appkey.

setVoice(String voice)

String

Sets the voice name.

setFormat(OutputFormatEnum format)

OutputFormatEnum

Sets the audio encoding format. The default is PCM.

setSampleRate(int sampleRate) / setSampleRate(SampleRateEnum sampleRate)

int / SampleRateEnum

Sets the sample rate in Hz. The SDK default is 24000.

setBitRate(int bitRate)

int

Sets the bitrate in kbit/s for OPUS audio.

setVolume(int volume)

int

Sets the volume from 0 to 100. The default is 50.

setSpeechRate(int speechRate)

int

Sets the speech rate from -500 to 500. The default is 0.

setPitchRate(int pitchRate)

int

Sets the pitch from -500 to 500. The default is 0.

addCustomedParam(String key, Object value)

String / Object

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

onSynthesisStart(StreamInputTtsResponse response)

The server is ready to synthesize speech.

onSentenceBegin(StreamInputTtsResponse response)

A sentence starts.

onSentenceSynthesis(StreamInputTtsResponse response)

Receives incremental timestamp information.

onSentenceEnd(StreamInputTtsResponse response)

A sentence ends, with sentence timestamps.

onSynthesisComplete(StreamInputTtsResponse response)

The synthesis task is complete.

onFail(StreamInputTtsResponse response)

The task fails. Read the task ID, status code, and error message from the response.

onAudioData(ByteBuffer buffer)

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

enable_aigc_tag

Boolean

Adds invisible AIGC metadata to WAV, MP3, or OPUS audio. The default is false.

aigc_propagator

String

Sets ContentPropagator, which identifies the content propagator. Defaults to the Alibaba Cloud UID. Takes effect when enable_aigc_tag is true.

aigc_propagate_id

String

Sets PropagateID, which identifies a propagation event. Defaults to the synthesis task ID. Takes effect when enable_aigc_tag is true.

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.