HarmonyOS Next SDK
This topic describes how to use the HarmonyOS Next NUI SDK for speech synthesis, including SDK integration, the call sequence, code examples, APIs, and callbacks.
Prerequisites
Review the parameters and limits for speech synthesis. For more information, see Speech synthesis mobile SDK reference.
Obtain a project Appkey. For more information, see Manage projects.
Obtain a valid NLS token (Access Token). For more information, see Obtain a token.
Obtain the NLS token on your application server and send it to the client. Do not embed or store an AccessKey ID or AccessKey secret on the client, or log tokens or initialization parameters that contain a token.
Download and integrate the SDK
Download harmony_neonui_sdk.tar.gz.
Extract the package and import
entry/libs/neonui.harinto your application. The package also provides C++ dynamic libraries and header files innative/libsandnative/include, respectively.Open the sample project in DevEco Studio. Set the Appkey and token in
entry/src/main/ets/Utils/UserKey.ets, then runentry/src/main/ets/pages/TTSPage.ets.
|
Item |
Compatibility |
|
System and development environment |
HarmonyOS Next 5.0, API level 12; DevEco Studio 5.0.3.403. |
|
Architecture |
arm64-v8a |
The SDK package supports the following features.
|
Feature |
Supported |
|
Short sentence recognition |
Yes |
|
Real-time speech recognition |
Yes |
|
Speech synthesis |
Yes |
|
Real-time long-text speech synthesis |
Yes |
|
Streaming text-to-speech |
Yes |
|
Offline speech synthesis |
No |
|
Flash recognition |
Yes |
|
Wake-up and command word recognition |
No |
|
Real-time audio streaming for Tingwu |
Yes |
Call sequence
Create SDK and player instances and implement
NuiTtsSdkListener.Call
tts_initialize, then callsetParamTtsto configure synthesis.Call
startTtsto start synthesis.Receive audio in
onTtsDataCallbackand write it to the player. Streaming playback is recommended.After
TTS_EVENT_END, let the player finish playing the audio already received.Call
tts_releasewhen the SDK is no longer needed.
SDK APIs are synchronous. Do not call them on the UI thread, where they can block the interface. To avoid deadlocks, do not call SDK APIs directly from SDK event callbacks. Schedule subsequent SDK operations outside the callback.
Code examples
The following snippets show SDK calls, not a standalone application page. For the complete page, see TTSPage.ets in the SDK package. The application wrapper is entry/src/main/ets/neonui/TTS.ets. Use resourceDir + "/resources_cloud" from the application context as the resource directory and a writable filesDir as the debug directory.
The examples create an instance with the constructor. You can also obtain the singleton by calling NativeNui.GetInstance(). Release an instance before initializing it again.
Initialize the SDK
The callback parameter is the listener implementation below. The application provides the paths and authentication parameters.
import { NativeNui, Constants, NuiTtsSdkListener, NuiSdkTtsEvent } from 'neonui';
function createSynthesizer(callback: NuiTtsSdkListener, resourceDir: string,
appkey: string, token: string, deviceId: string): NativeNui {
const nui = new NativeNui(Constants.ModeType.MODE_TTS, '');
const ticket: Record<string, string> = {
app_key: appkey,
token: token,
device_id: deviceId,
url: 'wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1',
mode_type: '2',
workspace: resourceDir + '/resources_cloud'
};
const ret = nui.tts_initialize(callback, JSON.stringify(ticket),
Constants.LogLevel.LOG_LEVEL_VERBOSE, false);
if (ret !== Constants.NuiResultCode.SUCCESS) {
throw new Error('tts_initialize failed: ' + ret);
}
return nui;
}
Configure synthesis
The player sample rate must match the synthesis sample rate. Set enable_subtitle to "1" to enable word-level phoneme boundaries or "0" to disable them. This parameter applies only to voices that support the feature. Long-text synthesis requires separate activation and is billed differently from short-text synthesis.
function configureSynthesizer(nui: NativeNui, text: string, longText: boolean): void {
nui.setParamTts('font_name', 'xiaoyun');
nui.setParamTts('sample_rate', '16000');
nui.setParamTts('enable_subtitle', '1');
// Optional synthesis parameters:
// nui.setParamTts('speed_level', '1');
// nui.setParamTts('pitch_level', '0');
// nui.setParamTts('volume', '1.0');
// const customParams: Record<string, boolean> = { enable_phoneme_timestamp: true };
// nui.setParamTts('custom_params', JSON.stringify(customParams));
const charNum = nui.getUtf8CharsNum(text);
if (longText || charNum > 300) {
nui.setParamTts('tts_version', '1');
} else {
nui.setParamTts('tts_version', '0');
}
}
Short-text mode synthesizes up to 300 characters per request and truncates text beyond the limit. A Chinese character, an English letter, or a punctuation mark counts as one character, excluding SSML markup. Set tts_version="1" for long-text mode or tts_version="0" for short-text mode.
Start synthesis
function startSynthesis(nui: NativeNui, text: string): number {
return nui.startTts('1', '', text);
}
Handle callbacks
The PlaybackController interface below represents application playback controls and must be connected to the player. prepare prepares playback, write queues audio, and finishInput marks the end of incoming audio while allowing queued audio to finish. stop stops playback immediately; pause and resume control playback. The SDK package provides the AudioPlayer wrapper.
interface PlaybackController {
prepare(): void;
write(buffer: ArrayBuffer): void;
finishInput(): void;
pause(): void;
resume(): void;
stop(): void;
}
class TtsCallbackHandle implements NuiTtsSdkListener {
private player: PlaybackController;
constructor(player: PlaybackController) {
this.player = player;
}
onTtsEventCallback(event: NuiSdkTtsEvent, taskid: string, ret_code: number): void {
if (event === NuiSdkTtsEvent.TTS_EVENT_START) {
this.player.prepare();
} else if (event === NuiSdkTtsEvent.TTS_EVENT_END) {
this.player.finishInput();
} else if (event === NuiSdkTtsEvent.TTS_EVENT_PAUSE) {
this.player.pause();
} else if (event === NuiSdkTtsEvent.TTS_EVENT_RESUME) {
this.player.resume();
} else if (event === NuiSdkTtsEvent.TTS_EVENT_CANCEL ||
event === NuiSdkTtsEvent.TTS_EVENT_ERROR) {
this.player.stop();
if (event === NuiSdkTtsEvent.TTS_EVENT_ERROR) {
console.error('synthesis error: ' + ret_code + ', task: ' + taskid);
}
}
}
onTtsDataCallback(info: string, info_len: number, buffer: ArrayBuffer | null): void {
if (buffer && buffer.byteLength > 0) {
this.player.write(buffer);
} else if (info) {
console.info(info);
}
}
onTtsVolCallback(vol: number): void {
}
}
Cancel synthesis
function cancelSynthesis(nui: NativeNui): number {
return nui.cancelTts('');
}
Release resources
function releaseSynthesizer(nui: NativeNui): number {
return nui.tts_release();
}
Key APIs and parameters
For parameter descriptions and conditions, see the API reference. For return codes and troubleshooting, see the Error code reference.
Initialization
tts_initialize(callback: NuiTtsSdkListener, ticket: string,
level: number, save_log: boolean): number
ticket is a JSON string. A lower level produces more logs. save_log controls whether logs are saved to debug_path. Log files have no size limit and must be cleaned up.
|
Parameter |
Type |
Required |
Description |
|
workspace |
String |
Yes |
Working directory from which the SDK reads configuration files. Read and write permissions are required. |
|
app_key |
String |
Yes |
Project Appkey. |
|
token |
String |
Yes |
Valid NLS token. Set it during initialization or update it through the parameter API. |
|
device_id |
String |
Yes |
Unique device or account identifier assigned by the application. |
|
mode_type |
String |
Yes |
Must be |
Synthesis parameters
setParamTts(param: string, value: string): number
getparamTts(param: string): string
getUtf8CharsNum(text: string): number
setParamTts sets a string parameter value, and getparamTts reads a parameter value. getUtf8CharsNum returns the character count. Set the required tts_version parameter to "0" for short text or "1" for long text. The optional custom_params parameter accepts a JSON string for additional parameters supported by the interaction protocol.
Tasks and resource management
startTts(priority: string, taskid: string, text: string): number
cancelTts(taskid: string): number
pauseTts(): number
resumeTts(): number
tts_release(): number
startTts starts synthesis. Set priority to "1". For taskid, pass a 32-byte UUID or an empty string to let the SDK generate the ID. text is the text to synthesize. Each instance handles one task; create multiple instances to handle multiple tasks at the same time. cancelTts cancels the specified task, or all tasks when passed an empty string. pauseTts and resumeTts pause and resume a task. tts_release releases SDK resources.
Callbacks and events
Implement the following three callbacks of NuiTtsSdkListener.
onTtsEventCallback(event: NuiSdkTtsEvent, taskid: string, ret_code: number): void
onTtsDataCallback(info: string, info_len: number, buffer: ArrayBuffer | null): void
onTtsVolCallback(vol: number): void
taskid is the task ID. ret_code provides the error code for TTS_EVENT_ERROR. When enable_subtitle is enabled, data callbacks alternate between timestamp information and audio: info contains JSON timestamps, info_len is not used, and a non-null buffer contains audio for the player. onTtsVolCallback reports volume.
|
Event |
Description |
|
TTS_EVENT_START |
Synthesis starts. Prepare playback. |
|
TTS_EVENT_END |
All synthesized audio has been returned. This does not mean playback has finished. |
|
TTS_EVENT_CANCEL |
Synthesis canceled. |
|
TTS_EVENT_PAUSE |
Synthesis paused. |
|
TTS_EVENT_RESUME |
Synthesis resumed. |
|
TTS_EVENT_ERROR |
Synthesis error. Call |
FAQ
How do I handle an unresponsive application when calling cancelTts?
SDK APIs are synchronous. Do not call them on the main thread.
How do I handle TTS_EVENT_ERROR with error code 140002?
Check whether the input text is valid.
What should I check if synthesis does not work?
Check that the prerequisites in this topic are met and that the Commercial Edition is activated.
What should I do if the sample crashes in the emulator?
Emulators may have compatibility issues. Use a physical device.
What is the maximum text length?
The boundary between short and long text is 300 characters. Set tts_version="0" for up to 300 characters and "1" for more than 300 characters. Otherwise, text beyond the short-text limit is truncated.
For a configuration example, see Configure synthesis.
How do I handle an unresponsive application caused by SDK call timeouts?
Avoid synchronous calls on the UI thread. For thread scheduling, see TtsWorker.ets in the SDK package.