Android SDK
Use the Android NUI SDK to synthesize speech from text and receive audio data through callbacks. This topic describes SDK integration, the call sequence, code examples, key interfaces, and troubleshooting.
Prerequisites
Activate Intelligent Speech Interaction and obtain a project Appkey. For project configuration, see Manage projects.
Obtain an NLS token. For instructions, see Obtain an access token.
Keep the AccessKey ID and AccessKey secret on the server. Do not include them in app code or store them on a mobile device. Cloud-based speech synthesis uses an Appkey and an NLS token for authentication. Obtain the token on the server, send it to the app, and update it before it expires. Initialization parameters contain credentials and should not be logged in full.
For synthesis parameters and supported voices, see Text-to-speech API reference for mobile clients.
Download and integrate the SDK
Download an Android NUI SDK package that supports speech synthesis from Select and download a mobile SDK. That topic provides version and compatibility information, the privacy policy, and compliance instructions.
The following examples use the V2.7.4-01B-20260831_Android_TLS package.
-
Extract the SDK package. Copy
app/libs/nuisdk-release.aarfrom the demo to the application module'slibsdirectory, then add the dependency to the module'sbuild.gradle:dependencies { implementation files('libs/nuisdk-release.aar') } -
Declare network access permission in
AndroidManifest.xml:<uses-permission android:name="android.permission.INTERNET" /> Open the demo project in Android Studio. The speech synthesis example is in
TtsBasicActivity.java. Replace the Appkey and token to run it.
Java interfaces are integrated through the AAR. The android_libs and android_include directories in the package contain the dynamic libraries and headers for C++ interfaces. Starting with SDK V2.6.2, cloud-only features do not require copying resource files or setting workspace.
Call sequence
Create SDK and player instances, set the callbacks, and initialize the SDK.
Call
setparamTtsto set the voice, audio format, sample rate, and other parameters.Call
startTtsto start synthesis.Receive audio data in
onTtsDataCallback. Write it to the player for streaming playback, or append successive chunks to the same file.After
TTS_EVENT_END, notify the player that all audio data has been sent and let it continue processing buffered data. This event indicates the end of synthesis, not playback.Call
tts_releasewhen the SDK is no longer needed, and release player resources.
Code examples
The following example uses AudioPlayer.java and AudioPlayerCallback.java from the demo. Playback uses 16 kHz, 16-bit, mono PCM. Add these classes and fastjson-1.1.46.android.jar from the demo's app/libs directory to the application module. Also declare a dependency on the JAR in build.gradle.
Use NativeNui.GetInstance() to obtain a singleton, or new NativeNui(Constants.ModeType.MODE_TTS) to create an instance. The example below uses an independent instance and runs one synthesis task at a time on it. Control methods such as initialization and cancellation are synchronous. Run them sequentially off the UI thread.
Configure the gateway
Declare the gateway constant in TtsExampleActivity below:
private static final String GATEWAY = "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1";
Initialization, synthesis, and callbacks
import android.util.Log;
import com.alibaba.idst.nui.Constants;
import com.alibaba.idst.nui.INativeTtsCallback;
import com.alibaba.idst.nui.NativeNui;
import mit.alibaba.nuidemo.AudioPlayer;
import mit.alibaba.nuidemo.AudioPlayerCallback;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.UUID;
public class SpeechSynthesizer implements INativeTtsCallback {
private final NativeNui nui = new NativeNui(Constants.ModeType.MODE_TTS);
private final AudioPlayer player;
private volatile boolean taskActive;
public SpeechSynthesizer(Runnable onPlaybackFinished) {
player = new AudioPlayer(new AudioPlayerCallback() {
@Override public void playStart() {}
@Override public void playOver() {
if (onPlaybackFinished != null) onPlaybackFinished.run();
}
@Override public void playSoundLevel(int level) {}
});
}
public int initialize(String appkey, String token, String gateway) throws JSONException {
JSONObject ticket = new JSONObject()
.put("app_key", appkey)
.put("token", token)
.put("url", gateway)
.put("mode_type", "2")
.put("device_id", UUID.randomUUID().toString());
int code = nui.tts_initialize(this, ticket.toString(),
Constants.LogLevel.LOG_LEVEL_NONE, false);
if (code != 0) return code;
code = nui.setparamTts("font_name", "xiaoyun");
if (code != 0) return code;
code = nui.setparamTts("sample_rate", "16000");
if (code != 0) return code;
code = nui.setparamTts("encode_type", "pcm");
if (code != 0) return code;
code = nui.setparamTts("enable_audio_decoder", "0");
if (code != 0) return code;
return nui.setparamTts("tts_version", "0");
}
public int setParameter(String name, String value) {
return nui.setparamTts(name, value);
}
public int start(String text) {
player.clearAudioQueue();
taskActive = true;
int code = nui.startTts("1", "", text);
if (code != 0) taskActive = false;
return code;
}
public int cancel() { return nui.cancelTts(""); }
public int pause() { return nui.pauseTts(); }
public int resume() { return nui.resumeTts(); }
public int close() {
if (taskActive) nui.cancelTts("");
player.stop();
int code = nui.tts_release();
player.releaseAudioTrack();
return code;
}
@Override public void onTtsEventCallback(TtsEvent event, String taskId, int code) {
if (event == TtsEvent.TTS_EVENT_START) {
player.play();
} else if (event == TtsEvent.TTS_EVENT_END) {
taskActive = false;
player.isFinishSend(true);
} else if (event == TtsEvent.TTS_EVENT_CANCEL || event == TtsEvent.TTS_EVENT_ERROR) {
taskActive = false;
player.stop();
if (event == TtsEvent.TTS_EVENT_ERROR) Log.e("TTS", "Synthesis failed: " + code);
} else if (event == TtsEvent.TTS_EVENT_PAUSE) {
player.pause();
} else if (event == TtsEvent.TTS_EVENT_RESUME) {
player.resume();
}
}
@Override public void onTtsDataCallback(String info, int infoLength, byte[] data) {
if (info != null && !info.isEmpty()) Log.i("TTS", "Subtitle: " + info);
if (data != null && data.length > 0) player.setAudioData(data);
}
@Override public void onTtsVolCallback(int volume) {}
}
The following activity initializes and starts synthesis on a serial queue, then releases resources when the activity is destroyed. Replace YOUR_APPKEY and YOUR_NLS_TOKEN with values supplied by the server, and add the gateway constant above.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TtsExampleActivity extends Activity {
private final ExecutorService ttsQueue = Executors.newSingleThreadExecutor();
private SpeechSynthesizer synthesizer;
@Override protected void onCreate(Bundle state) {
super.onCreate(state);
synthesizer = new SpeechSynthesizer(() -> Log.i("TTS", "Playback queue completed"));
ttsQueue.execute(() -> {
try {
int code = synthesizer.initialize("YOUR_APPKEY", "YOUR_NLS_TOKEN", GATEWAY);
if (code == 0) code = synthesizer.start("Hello, welcome to the speech synthesis example.");
if (code != 0) Log.e("TTS", "Start failed: " + code);
} catch (JSONException error) {
Log.e("TTS", "Failed to build initialization parameters");
}
});
}
@Override protected void onDestroy() {
ttsQueue.execute(() -> {
int code = synthesizer.close();
if (code != 0) Log.e("TTS", "Release failed: " + code);
});
ttsQueue.shutdown();
super.onDestroy();
}
}
To cancel, pause, or resume, call synthesizer.cancel(), synthesizer.pause(), or synthesizer.resume() on the same queue. close() stops the player and releases resources. Release SDK resources on the control queue, rather than directly in an SDK callback.
Configure synthesis parameters
Insert the following snippet after the activity's initialize call and before start, reusing its code variable. You can set speech rate, pitch, and volume as needed:
if (code == 0) code = synthesizer.setParameter("speed_level", "0.6");
if (code == 0) code = synthesizer.setParameter("pitch_level", "100");
if (code == 0) code = synthesizer.setParameter("volume", "0.6");
Select a voice that supports timestamps and enable enable_subtitle, then obtain the result from info in onTtsDataCallback. You can also pass parameters supported by the interaction protocol through custom_params, whose value is a JSON string:
if (code == 0) code = synthesizer.setParameter("font_name", "siyue");
if (code == 0) code = synthesizer.setParameter("enable_subtitle", "1");
// Alternatively, pass the setting in a JSON string.
String params = new JSONObject().put("enable_subtitle", true).toString();
// if (code == 0) code = synthesizer.setParameter("custom_params", params);
After applying the snippet, proceed to start only if the return value is 0. If changing the synthesis sample rate, also use AudioPlayer.setSampleRate to set the same rate on the player.
Synthesize long text
Short-text mode supports up to 300 characters per request and truncates any excess. Each Chinese character, English letter, or punctuation mark counts as one character. Long-text speech synthesis must be activated separately and is billed differently from short-text synthesis.
The following snippet handles plain text. Use it to replace the activity's start call after successful initialization:
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 12; i++) builder.append("This is a long text synthesis example. ");
String text = builder.toString();
if (code == 0) code = synthesizer.setParameter("tts_version", "1");
if (code == 0) code = synthesizer.start(text);
Use the getUtf8CharsNum method on a NativeNui instance to count characters in plain text. The method counts the supplied string, including SSML tag characters. For SSML, select the synthesis mode based on the length of the actual text content.
Key interfaces and callbacks
Initialization parameters
ticket is the JSON string passed to tts_initialize.
|
Parameter |
Type |
Description |
|
|
String |
Required. The Appkey of the console project. |
|
|
String |
Required. A valid, unexpired NLS token. Set it during initialization or update it with |
|
|
String |
Required. An identifier supplied by the caller. We recommend a unique value to help locate issues. |
|
|
Integer or String |
Required. Use |
|
|
String |
The service gateway. The example sets it explicitly. |
|
|
String |
The resource directory. Starting with V2.6.2, cloud-only features do not require it. Features that depend on local resources require a directory with read and write permissions. |
|
|
String |
The log directory. When |
Synthesis parameters
Set synthesis parameters with setparamTts. Parameter values are strings.
|
Parameter |
Example value |
Description |
|
|
|
The voice. |
|
|
|
The synthesis sample rate. It must match the player sample rate. |
|
|
|
The output format. The example uses PCM. |
|
|
|
Enables timestamps for voices that support them. Use |
|
|
|
The speech rate. |
|
|
|
The pitch. |
|
|
|
The volume. |
|
|
|
The synthesis mode. The default |
|
|
JSON string |
Configures other parameters supported by the interaction protocol. Use |
Use tts_version="1" for long-text speech synthesis. For more parameters and supported voices, see Text-to-speech API reference for mobile clients.
Control methods
Except for getparamTts, which returns a parameter value, the following methods return integer status codes. A value of 0 indicates a successful call. Asynchronous synthesis errors are reported through TTS_EVENT_ERROR.
For error codes and solutions, see Error code reference.
Initialization and parameter settings
tts_initialize: Initializes the SDK. Release SDK resources before initializing it again. Initialization may block and should run off the UI thread.
public synchronized int tts_initialize(INativeTtsCallback callback,
String ticket, Constants.LogLevel level, boolean save_log);
callback: TheINativeTtsCallbackevent and data callbacks.ticket: A JSON string of initialization parameters.level: The log level. Lower enum values produce more detailed logs.save_log: Whether to save logs to files. The directory is specified bydebug_pathinticket. When enabled, monitor storage capacity and clean up logs regularly.
setparamTts: Sets a synthesis parameter by name and value.
public synchronized int setparamTts(String param, String value);
param is the parameter name, and value is its value.
Synthesis task control
startTts: Starts synthesis. Audio is delivered to the app through callbacks for playback or storage.
public synchronized int startTts(String priority, String taskid, String text);
priority: The task priority. Use"1".taskid: The task ID. Pass a 32-byte UUID or an empty string to let the SDK generate an ID.text: The text to synthesize.
cancelTts: Cancels synthesis. taskid identifies the task to cancel. Pass an empty string to cancel all tasks.
public synchronized int cancelTts(String taskid);
pauseTts / resumeTts: Pauses or resumes a synthesis task. The app controls the player's pause and resume behavior. The example calls player methods in response to the corresponding events.
public synchronized int pauseTts();
public synchronized int resumeTts();
Parameter queries and resource release
getparamTts: Queries a parameter. param is the name, and the return value is its value. Query "error_msg" for detailed error information.
public String getparamTts(String param);
tts_release: Releases SDK resources.
public synchronized int tts_release();
Data and volume callbacks
INativeTtsCallback includes the following callbacks. onTtsDataCallback returns synthesized audio. When timestamps are enabled and the voice supports them, it also returns timestamp information in JSON format.
void onTtsDataCallback(String info, int info_len, byte[] data);
void onTtsVolCallback(int volume);
info: Timestamp information. Timestamp information and audio data may arrive in different callbacks. Check and handle each separately.info_len: The length ofinfo.data: Synthesized audio data to write to the player or a file.volume: The volume callback value. Implement this method even if the app does not use volume callbacks.
Event callback
void onTtsEventCallback(TtsEvent event, String task_id, int ret_code);
event is the event type, and task_id is the task ID. ret_code is an error code that is valid for TTS_EVENT_ERROR.
|
Event |
Description |
|
|
Synthesis starts. Prepare for playback. |
|
|
Synthesis ends. All audio has been delivered through callbacks, but the player may still have buffered data. |
|
|
The synthesis task is canceled. |
|
|
The synthesis task is paused. |
|
|
The synthesis task is resumed. |
|
|
An error occurs during synthesis. Use |
FAQ
How do I resolve an ANR when calling the cancel method?
SDK control methods are synchronous. Run methods such as initialization and cancellation sequentially off the UI thread to avoid blocking the main thread.
How do I resolve error 140002?
This error indicates invalid synthesis text, such as an empty string. Check that the input text is valid and non-empty, then use getparamTts("error_msg") for detailed error information.
How do I troubleshoot a speech synthesis failure?
Verify that the prerequisites are met, then check the activation status and available quota for the service in use. If the trial has expired or the corresponding service is not activated for a commercial request, activate the commercial edition.
How do I troubleshoot a crash on an emulator?
Verify that the SDK package includes an ABI matching the emulator, then check system compatibility and the crash log. You can investigate device-specific issues on a physical device.
How do I resolve file access error 240021?
Check read and write permissions for the configured resource or log directory. If using an SDK feature that depends on configuration files, also verify that the resource files have been copied. Cloud-only synthesis does not require resource files starting with V2.6.2. For more error codes, see Error code reference.