C++ SDK
Use the C++ SDK to synthesize long text into audio in real time and receive audio data and task status through callbacks.
Prerequisites and limitations
Activate the commercial edition of real-time long-text speech synthesis.
Prepare an Alibaba Cloud AccessKey ID and AccessKey secret with the required permissions. For instructions, see Create an AccessKey pair.
Use UTF-8 text. For parameters, voices, and service endpoints, see Real-time long-text speech synthesis API reference.
Obtain and install the SDK
Build from source
Obtain the source code from GitHub or download the source archive:
git clone --depth 1 https://github.com/aliyun/alibabacloud-nls-cpp-sdk| SDK package | Platform | MD5 |
SDK source code | 7257c0998654e611cf2e8ca9867670ef |
The source package requires CMake 3.8, Glibc 2.5, and GCC 4.8.5 or later for building. Runtime dependencies of precompiled libraries depend on the selected package. Build from the source root directory:
./scripts/build_linux.sh
The build generates srDemo for short sentence recognition, stDemo for real-time speech recognition, syDemo for speech synthesis, and daDemo for voice dialog. Run syDemo to view its usage:
cd build/demo
./syDemo
Precompiled packages
Select an SDK package for the target architecture. These packages contain headers and precompiled libraries, so the SDK does not need to be compiled. Follow the package's readme.md for integration instructions. Package names include the platform, version, and Git commit ID.
| SDK package | Platform | MD5 |
Linux x86_64 | 9a93df607f26f1558bc1043a425af6d1 | |
Linux aarch64 | 76c34a3ab397d7285963a139b9270ff4 |
The Linux x86_64 3.3.0b Release_CXX11 library requires GLIBC 2.17 and GLIBCXX 3.4.21 or later. Check the package instructions for other build variants and select libraries with an ABI compatible with the application.
SDK package files
scripts/build_linux.sh builds the SDK on Linux, and CMakeLists.txt configures the sample project. lib contains SDK libraries. readme.md, release.log, and version provide usage instructions, release notes, and the version number, respectively.
demo
File name | Description |
speechRecognizerDemo.cpp | Example for short sentence recognition. |
speechSynthesizerDemo.cpp | Example for speech synthesis. |
speechTranscriberDemo.cpp | Example for real-time speech recognition. |
fileTransferDemo.cpp | Example for audio file recognition. |
resource
Contains sample audio at 16 kHz with a 16-bit sample depth:
File name | Description |
| Test audio files (16 kHz audio sampling rate, 16-bit audio bit depth). |
include
File name | Description |
nlsClient.h | SDK instance. |
nlsEvent.h | Callback event description. |
nlsGlobal.h | Global SDK header file. |
nlsToken.h | SDK Access Token instance. |
iNlsRequest.h | Base header file for NLS requests. |
speechRecognizerRequest.h | Short sentence recognition. |
speechSynthesizerRequest.h | Speech synthesis and long-text speech synthesis. |
speechTranscriberRequest.h | Real-time audio stream recognition. |
FileTrans.h | Audio file recognition. |
Code example
This example uses SDK 3.3.0b. Configure the following environment variables:
NLS_APPKEY_ENV: Project Appkey.NLS_AK_ENV: Alibaba Cloud AccessKey ID.NLS_SK_ENV: Alibaba Cloud AccessKey secret.
The example initializes the client and synthesis request and writes received audio to long-synthesis.wav. It handles completion, failure, and channel closure through callbacks. Avoid time-consuming operations in callbacks.
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <mutex>
#include <string>
#include <vector>
#include "nlsClient.h"
#include "nlsEvent.h"
#include "nlsToken.h"
#include "speechSynthesizerRequest.h"
using namespace AlibabaNls;
struct SynthesisContext {
std::ofstream audio;
std::mutex mutex;
std::condition_variable condition;
bool closed = false;
bool completed = false;
bool failed = false;
};
void onAudio(NlsEvent* event, void* parameter) {
auto* context = static_cast<SynthesisContext*>(parameter);
const std::vector<unsigned char>& data = event->getBinaryData();
std::lock_guard<std::mutex> lock(context->mutex);
if (!data.empty()) {
context->audio.write(reinterpret_cast<const char*>(data.data()), data.size());
if (!context->audio) context->failed = true;
}
}
void onCompleted(NlsEvent* event, void* parameter) {
auto* context = static_cast<SynthesisContext*>(parameter);
std::lock_guard<std::mutex> lock(context->mutex);
context->completed = true;
std::cout << "Synthesis completed. TaskId: " << event->getTaskId() << '\n';
}
void onFailed(NlsEvent* event, void* parameter) {
auto* context = static_cast<SynthesisContext*>(parameter);
std::lock_guard<std::mutex> lock(context->mutex);
context->failed = true;
std::cerr << "Synthesis failed. TaskId: " << event->getTaskId()
<< ", status: " << event->getStatusCode()
<< ", message: " << event->getErrorMessage() << '\n';
}
void onClosed(NlsEvent*, void* parameter) {
auto* context = static_cast<SynthesisContext*>(parameter);
std::lock_guard<std::mutex> lock(context->mutex);
context->closed = true;
context->condition.notify_one();
}
int main() {
const char* appkey = std::getenv("NLS_APPKEY_ENV");
const char* accessKeyId = std::getenv("NLS_AK_ENV");
const char* accessKeySecret = std::getenv("NLS_SK_ENV");
if (!appkey || !*appkey || !accessKeyId || !*accessKeyId ||
!accessKeySecret || !*accessKeySecret) {
std::cerr << "Set NLS_APPKEY_ENV, NLS_AK_ENV, and NLS_SK_ENV.\n";
return 1;
}
NlsClient* client = NlsClient::getInstance();
// Obtain an NLS token with Alibaba Cloud AccessKey credentials.
AlibabaNlsCommon::NlsToken token;
token.setAccessKeyId(accessKeyId);
token.setKeySecret(accessKeySecret);
if (token.applyNlsToken() != 0) {
std::cerr << "Token request failed: " << token.getErrorMsg() << '\n';
NlsClient::releaseInstance();
return 1;
}
SynthesisContext context;
const char* outputFile = "long-synthesis.wav";
context.audio.open(outputFile, std::ios::binary | std::ios::out);
if (!context.audio) {
std::cerr << "Cannot open output file: " << outputFile << '\n';
NlsClient::releaseInstance();
return 1;
}
client->startWorkThread(1);
SpeechSynthesizerRequest* request = client->createSynthesizerRequest(LongTts);
if (!request) {
NlsClient::releaseInstance();
std::cerr << "Cannot create synthesis request.\n";
return 1;
}
request->setOnBinaryDataReceived(onAudio, &context);
request->setOnSynthesisCompleted(onCompleted, &context);
request->setOnTaskFailed(onFailed, &context);
request->setOnChannelClosed(onClosed, &context);
request->setAppKey(appkey);
request->setToken(token.getToken());
request->setUrl("wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1");
request->setText("Welcome to Intelligent Speech Interaction.");
request->setVoice("siqi");
request->setFormat("wav");
request->setSampleRate(16000);
request->setVolume(50);
request->setSpeechRate(0);
request->setPitchRate(0);
int result = request->start();
if (result < 0) {
std::cerr << "Cannot start synthesis: " << result << '\n';
} else {
std::unique_lock<std::mutex> lock(context.mutex);
bool closed = context.condition.wait_for(
lock, std::chrono::seconds(60), [&context] { return context.closed; });
if (!closed) {
context.failed = true;
std::cerr << "Synthesis timed out.\n";
lock.unlock();
request->cancel();
}
}
// Release the request before the client, then close the output file.
client->releaseSynthesizerRequest(request);
NlsClient::releaseInstance();
context.audio.close();
if (result < 0 || context.failed || !context.completed || !context.audio) return 1;
std::cout << "Audio saved to " << outputFile << '\n';
return 0;
}
Production applications can cache the NLS token and refresh it based on the expiration time returned by getExpireTime(). See Obtain a token. For VPC access from an ECS instance in the China (Shanghai) region, set the URL to ws://nls-gateway-cn-shanghai-internal.aliyuncs.com:80/ws/v1. For other service endpoints, see Real-time long-text speech synthesis API reference.
Key interfaces
NlsClient
The following interfaces apply to SDK 3.x and differ from the retired SDK 2.0 interfaces. NlsClient is a thread-safe speech client. Reuse one instance per process. Start its worker threads before creating requests, and destroy the client only after all requests are released.
Interface | Enable versioning | Description |
getInstance | 2.x | Get (create) an NlsClient instance. |
setLogConfig | 2.x | Set the log file and storage path. |
setDirectHost | 3.x | Directly set the server IPv4 address to skip DNS domain name resolution. If you call this interface, you must call it before startWorkThread. |
setAddrInFamily | 3.1.12 | Set the type of the socket address structure. The default value is AF_INET, which returns only IPv4-related address information. You must call this interface before startWorkThread. |
setUseSysGetAddrInfo | 3.1.13 | If the DNS of libevent fails and cannot complete DNS resolution, you can call this interface to switch to the system's interface. You must call this interface before startWorkThread. |
calculateUtf8Chars | 3.1.14 | Count the number of characters in the text. You must pass the text content in UTF-8 encoding. One Chinese character, one English letter, or one punctuation mark is counted as one character. |
setSyncCallTimeout | 3.1.17 | Sets the synchronous call timeout in milliseconds. The default is 0, which disables synchronous mode. In synchronous mode, |
setPreconnectedPool | 3.3.0 | Configures a preconnected pool for each domain URL. Connections are reused after requests to reduce connection setup time and first-packet latency. Enabling it disables long-connection mode. It does not apply to Tingwu. Call it before |
startWorkThread | 3.x | Starts SDK worker threads. Call this method before creating and starting requests. The default is 1, which starts one thread. Set it to -1 to start as many threads as there are CPU cores. For high concurrency, we recommend -1. |
getVersion | 3.x | Get the SDK version number. |
releaseInstance | 2.x | Destroy the NlsClient object instance. |
| createSynthesizerRequest | 2.x | Creates a synthesis request. Use |
releaseSynthesizerRequest | 2.x | Destroy the speech synthesis object. You must call this interface after the closed event of the current request. |
NlsToken
NlsToken requests an NLS token and provides its expiration time.
Interface | Description |
setAccessKeyId | Set the AccessKey ID of your Alibaba Cloud account. |
setKeySecret | Set the AccessKey secret of your Alibaba Cloud account. |
setDomain | Set the domain name. This parameter is optional. |
setServerVersion | Set the API version. This parameter is optional. |
setServerResourcePath | Set the service path. This parameter is optional. |
setRegionId | Sets the service region ID. Optional. |
setAction | Set the feature. This parameter is optional. |
applyNlsToken | Request a Token ID. |
getToken | Get the Token ID. |
getExpireTime | Get the expiration timestamp (in seconds) of the token. |
getErrorMsg | Get the error message. |
NlsEvent
NlsEvent provides request status, task IDs, audio data, and server responses.
Interface | Description |
getStatusCode | Get the status code. A value of 0 or 20000000 indicates success. Other values indicate a failure. |
getErrorMessage | In the TaskFailed callback, get the error message that occurs during the NlsRequest operation. |
getTaskId | Get the TaskId of the task. |
getBinaryData | Get the binary data returned from the cloud. |
getAllResponse | Gets the complete response returned by the server. |
SpeechSynthesizerRequest
SpeechSynthesizerRequest configures synthesis text, voice, output format, and callbacks. For parameter values and supported voices, see Real-time long-text speech synthesis API reference.
Interface | Enable versioning | Description |
setOnSynthesisCompleted | 2.x | Set the callback function for when speech synthesis is complete. |
setOnChannelClosed | 2.x | Set the callback function for when the channel is closed. |
setOnTaskFailed | 2.x | Set the callback function for errors. |
setOnBinaryDataReceived | 2.x | Set the callback function for receiving binary audio data from speech synthesis. |
setOnMetaInfo | 2.x | Sets the callback for metadata, such as subtitles. |
setOnMessage | 3.1.16 | Set the callback function for server response messages. All callbacks are output from this callback for you to parse. This parameter is optional. After setting it, you must call setEnableOnMessage to enable it. |
setAppKey | 2.x | Set the AppKey. |
setToken | 2.x | Sets the NLS token for request authentication. |
setUrl | 2.x | Set the service URL. This parameter is optional. |
setText | 2.x | Sets the UTF-8 text to synthesize. |
setVoice | 2.x | Set the voice. |
setVolume | 2.x | Set the volume. |
setFormat | 2.x | Set the output audio encoding format. The default value is PCM. Supported formats are PCM, WAV, and MP3. |
setSampleRate | 2.x | Set the audio sampling rate. |
setSpeechRate | 2.x | Set the speech rate. |
setPitchRate | 2.x | Set the pitch. |
setMethod | 2.x | Set the synthesis method. The default value is 0.
|
setEnableSubtitle | 2.x | Enable the caption feature. |
setPayloadParam | 2.x | Set parameters. The input parameter is a JSON-formatted string. |
setTimeout | 2.x | Sets the connection timeout in milliseconds. The default in SDK 3.3.0b is 500. |
setContextParam | 2.x | Set custom user parameters. The input parameter is a JSON-formatted string. |
AppendHttpHeaderParam | 2.x | Set custom HTTP header parameters for the WebSocket phase. |
setSendTimeout | 3.1.14 | Set the sending timeout period. The default value is 5000 ms. |
setEnableOnMessage | 3.1.16 | Enable the callback for messages returned by the server. |
getTaskId | 3.1.17 | Get the task_id of the current request. |
start | 2.x | Start the SpeechSynthesizerRequest. |
cancel | 2.x | Directly close the speech synthesis process without confirming the closure with the server. |
To synthesize speech with emotions, use a voice that supports multiple emotions and include an <emotion> tag in text. For details, see SSML.
Error handling
The following tables list local SDK return codes and their handling methods. For server response status codes, see Error codes.
Status code | Status message | Cause | Solution |
0 | Success | Success | |
-10 | DefaultError | Default error | Not in use. |
-11 | JsonParseFailed | Invalid JSON format | Check whether the input JSON string is in the valid JSON format. |
-12 | JsonObjectError | Invalid JSON object | Retry the operation. |
-13 | MallocFailed | Malloc failed | Check whether the memory is sufficient. |
-14 | ReallocFailed | Realloc failed | Check whether the memory is sufficient. |
-15 | InvalidInputParam | Invalid input parameter | Not in use. |
-50 | InvalidLogLevel | Invalid log level | Check the configured log level. |
-51 | InvalidLogFileSize | Invalid log file size | Check the configured log file size parameter. |
-52 | InvalidLogFileNum | Invalid number of log files | Check the configured parameter for the number of log files. |
-100 | EncoderExistent | The NLS encoder already exists | Retry the operation. |
-101 | EncoderInexistent | The NLS encoder does not exist | We recommend re-initializing. |
-102 | OpusEncoderCreateFailed | Failed to create the Opus encoder | We recommend that you re-initialize. |
-103 | OggOpusEncoderCreateFailed | Failed to create the OggOpus encoder | We recommend re-initialization. |
-104 | InvalidEncoderType | Invalid encoder type | OPUS may have been disabled at compile-time but is still being used. Alternatively, check ENCODER_TYPE. |
-150 | EventClientEmpty | The main worker thread is a null pointer and has been released | Re-initialize the SDK by calling startWorkThread(). |
-151 | SelectThreadFailed | Failed to select a worker thread. The thread is not initialized | Re-initialize the SDK by calling startWorkThread(). |
-160 | StartCommandFailed | Failed to send the start command | Retry the operation. |
-161 | InvokeStartFailed | The request state machine is incorrect, causing start to fail | Check whether the current request has not been created or has already been completed. |
-162 | InvokeSendAudioFailed | The request state machine is incorrect, causing sendAudio to fail | Check whether the current request has been started (that is, a started event callback has been received) or has already been completed. |
-163 | InvalidOpusFrameSize | Invalid Opus frame length. The default is 640 bytes | In OPU encoding mode, sendAudio accepts only 640 bytes of data per frame. |
-164 | InvokeStopFailed | The request state machine is incorrect, causing stop to fail | Verify that the current request has not yet started (the 'started' event callback has not been received) or is already complete. |
-165 | InvokeCancelFailed | The request state machine is incorrect, causing cancel to fail | Check if the current request has not yet started (the |
-166 | InvokeStControlFailed | The request state machine is incorrect, causing stControl to fail | Check if the current request has not started (the 'started' event callback has not been received) or is already complete. |
-200 | NlsEventEmpty | The NLS event is empty | For internal SDK use. The NlsEvent frame is lost. |
-201 | NewNlsEventFailed | Failed to create NlsEvent | For internal SDK use. Failed to create the NlsEvent frame. |
-202 | NlsEventMsgEmpty | The message in the NLS event is empty | The message string was found to be empty during parsing by parseJsonMsg(). |
-203 | InvalidNlsEventMsgType | Invalid message type in the NLS event | For internal SDK use. The event type of the NlsEvent frame is invalid. |
-204 | InvalidNlsEventMsgStatusCode | Invalid message status code in the NLS event | For internal SDK use. The event message status of the NlsEvent frame is invalid. |
-205 | InvalidNlsEventMsgHeader | Invalid message header in the NLS event | For internal SDK use. The event message header of the NlsEvent frame is invalid. |
-250 | CancelledExitStatus | cancel has been called | Not in use. |
-251 | InvalidWorkStatus | Invalid working status | For internal SDK use. The internal status of the current request is invalid. |
-252 | InvalidNodeQueue | The NodeQueue in workThread is invalid | For internal SDK use. The current request to be run is invalid. Release the current request and try again. |
-300 | InvalidRequestParams | Invalid input parameters for the request | The data passed to sendAudio is empty. |
-301 | RequestEmpty | The request is a null pointer | For internal SDK use. The current request has been released. Release the current request and try again. |
-302 | InvalidRequest | Invalid request | For internal SDK use. The current request has been released. Release the current request and try again. |
-303 | SetParamsEmpty | The input parameter is empty | Check whether the input parameter is empty. |
-350 | GetHttpHeaderFailed | Failed to get the HTTP header | For internal SDK use. Locate the issue based on the feedback in the logs. |
-351 | HttpGotBadStatus | HTTP error status | For internal SDK use. Locate the issue based on the feedback in the logs. |
-352 | WsResponsePackageFailed | Failed to parse the WebSocket response package | For internal SDK use. Locate the issue based on the feedback in the logs. |
-353 | WsResponsePackageEmpty | The parsed WebSocket response package is empty | For internal SDK use. Locate the issue based on the feedback in the logs. |
-354 | WsRequestPackageEmpty | The WebSocket request package is empty | For internal SDK use. Locate the issue based on the feedback in the logs. |
-355 | UnknownWsFrameHeadType | Unknown WebSocket frame header type | For internal SDK use. Locate the issue based on the feedback in the logs. |
-356 | InvalidWsFrameHeaderSize | Invalid WebSocket frame header size | For internal SDK use. Locate the issue based on the feedback in the logs. |
-357 | InvalidWsFrameHeaderBody | Invalid WebSocket frame header body | For internal SDK use. Locate the issue based on the feedback in the logs. |
-358 | InvalidWsFrameBody | Invalid WebSocket frame body | For internal SDK use. Locate the issue based on the feedback in the logs. |
-359 | WsFrameBodyEmpty | The frame data is empty. This is often caused by receiving dirty data | For internal SDK use. Locate the issue based on the feedback in the logs. |
-400 | NodeEmpty | The node is a null pointer | Release the current request and try again. |
-401 | InvaildNodeStatus | The node is in an invalid state | For internal SDK use. Release the current request and try again. |
-402 | GetAddrinfoFailed | Address detection using DNS parsing | For internal SDK use. Check whether DNS is available in the current environment. |
-403 | ConnectFailed | Network connection failed | Check whether the current network environment is available. |
-404 | InvalidDnsSource | No DNS on the current device | For internal SDK use. Check whether DNS is available in the current environment. |
-405 | ParseUrlFailed | Invalid URL | Check whether the configured URL is valid. |
-406 | SslHandshakeFailed | SSL handshake failed | For internal SDK use. Check whether the current network environment is available and try again. |
-407 | SslCtxEmpty | SSL_CTX is empty | For internal SDK use. Check whether the current network environment is available and try again. |
-408 | SslNewFailed | SSL_new failed | For internal SDK use. Check whether the current network environment is available and try again. |
-409 | SslSetFailed | Failed to set SSL parameters | For internal SDK use. Check whether the current network environment is available and try again. |
-410 | SslConnectFailed | SSL_connect failed | For internal SDK use. Check whether the current network environment is available and try again. |
-411 | SslWriteFailed | Failed to send data over SSL | For internal SDK use. Check whether the current network environment is available and try again. |
-412 | SslReadSysError | SYSCALL error received when receiving data over SSL | For internal SDK use. Check whether the current network environment is available and try again. |
-413 | SslReadFailed | Failed to receive data over SSL | For internal SDK use. Check whether the current network environment is available and try again. |
-414 | SocketFailed | Failed to create a socket | For internal SDK use. Check whether the current network environment is available and try again. |
-415 | SetSocketoptFailed | Failed to set socket parameters | For internal SDK use. Check whether the current network environment is available and try again. |
-416 | SocketConnectFailed | Failed to establish a socket connection | For internal SDK use. Check whether the current network environment is available and try again. |
-417 | SocketWriteFailed | Failed to send data over the socket | For internal SDK use. Check whether the current network environment is available and try again. |
-418 | SocketReadFailed | Failed to receive data from the socket | For internal SDK use. Check whether the current network environment is available and try again. |
-430 | NlsReceiveFailed | Failed to receive NLS frame data | For internal SDK use. Check whether the current network environment is available and try again. |
-431 | NlsReceiveEmpty | The received NLS frame data is empty | For internal SDK use. Check whether the current network environment is available and try again. |
-432 | ReadFailed | Failed to receive data | For internal SDK use. Check whether the current network environment is available and try again. |
-433 | NlsSendFailed | Failed to send NLS data | For internal SDK use. Check whether the current network environment is available and try again. |
-434 | NewOutputBufferFailed | Failed to create a buffer | For internal SDK use. Check whether the memory is sufficient. |
-435 | NlsEncodingFailed | Audio encoding failed | For internal SDK use. Release the current request and try again. |
-436 | EventEmpty | The event is empty | For internal SDK use. Release the current request and try again. |
-437 | EvbufferTooMuch | Too much data in evbuffer | For internal SDK use. The send data cache is full (maximum cache size is 320,000 for 16K audio and 160,000 for 8K audio). Check if audio data is being sent too frequently or if too much data is being sent at once. |
-438 | EvutilSocketFailed | Failed to set evutil parameters | For internal SDK use. Release the current request and try again. |
-439 | InvalidExitStatus | Invalid exit status | Check whether the current request has been canceled. |
-450 | InvalidAkId | Invalid AccessKey ID for the Alibaba Cloud account | Check whether the AccessKey ID for the Alibaba Cloud account is empty. |
-451 | InvalidAkSecret | Invalid AccessKey secret for the Alibaba Cloud account | Check whether the AccessKey secret for the Alibaba Cloud account is empty. |
-452 | InvalidAppKey | Invalid project AppKey | Check whether the Alibaba Cloud project AppKey is empty. |
-453 | InvalidDomain | Invalid domain | Check whether the input domain is empty. |
-454 | InvalidAction | Invalid action | Check whether the input action is empty. |
-455 | InvalidServerVersion | Invalid ServerVersion | Check whether the input ServerVersion is empty. |
-456 | InvalidServerResource | Invalid ServerResource | Check whether the input ServerResource is empty. |
-457 | InvalidRegionId | Invalid RegionId | Check whether the input RegionId is empty. |
-500 | InvalidFileLink | Invalid audio file link | The audio file link for transcription is empty. |
-501 | ErrorStatusCode | Error status code | An error was returned for audio file transcription. See the error code for details. |
-502 | IconvOpenFailed | Failed to request a conversion descriptor | Failed to convert between UTF-8 and GBK. |
-503 | IconvFailed | Encoding conversion failed | Failed to convert between UTF-8 and GBK. |
-504 | ClientRequestFaild | Account client request failed | Failed to return the result of audio file transcription. |
-999 | NlsMaxErrorCode |
Other status codes | Status message | Cause | Solution |
10000001 | NewSslCtxFailed | SSL: couldn't create a context! | We recommend reinitializing. |
10000002 | DefaultErrorCode | return of SSL_read: error:00000000:lib(0):func(0):reason(0) | Retry the operation. |
return of SSL_read: error:140E0197:SSL routines:SSL_shutdown:shutdown while in init | |||
10000003 | SysErrorCode | System error. | Handle the error based on the feedback from the system. |
10000004 | EmptyUrl | URL: The url is empty. | The input URL is empty. Enter a valid URL. |
10000005 | InvalidWsUrl | Could not parse WebSocket url: | The input URL is in an invalid format. Enter a valid URL. |
10000007 | JsonStringParseFailed | JSON: Json parse failed. | Invalid JSON format. Check the logs for the specific error point. |
10000008 | UnknownWsHeadType | WEBSOCKET: unkown head type. | Network connection failed. Check your local DNS resolution and whether the URL is valid. |
10000009 | HttpConnectFailed | HTTP: connect failed. | Failed to connect to the cloud. Check your network and try again. |
10000010 | MemNotEnough | Out of memory. | Check whether the memory is sufficient. |
10000015 | SysConnectFailed | connect failed. | Network connection failed. Check your local DNS resolution and whether the URL is valid. |
10000100 | HttpGotBadStatusWith403 | Got bad status host=xxxxx line=HTTP/1.1 403 Forbidden | The connection was rejected. Check your account, especially whether the token has expired. |
10000101 | EvSendTimeout | Send timeout. socket error: | libevent timed out when sending an event. Check whether there are time-consuming tasks in the callback, or whether high concurrency prevents timely event processing. |
10000102 | EvRecvTimeout | Recv timeout. socket error: | libevent timed out when receiving an event. Check whether there are time-consuming tasks in the callback, or whether high concurrency prevents timely event processing. |
10000103 | EvUnknownEvent | Unknown event: | Unknown libevent event. Retry the operation. |
10000104 | OpNowInProgress | Operation now in progress | The connection is in progress. Retry the operation. |
10000105 | BrokenPipe | Broken pipe | The pipe cannot be processed. Retry the operation. |
10000110 | TokenHasExpired | Gateway:ACCESS_DENIED:The token 'xxx' has expired! | Update the token. |
10000111 | TokenIsInvalid | Meta:ACCESS_DENIED:The token 'xxx' is invalid! | Check the validity of the token. |
10000112 | NoPrivilegeToVoice | Gateway:ACCESS_DENIED:No privilege to this voice! (voice: zhinan, privilege: 0) | You do not have permission to use this voice. |
10000113 | MissAuthHeader | Gateway:ACCESS_DENIED:Missing authorization header! | Check whether your account has the required permissions, or whether the concurrency is within the limit. |
10000120 | Utf8ConvertError | utf8ToGbk failed | UTF-8 transcoding failed. This is often a system issue. Retry the operation. |
20000000 | SuccessStatusCode | Success |
FAQ
Can I use GCC versions later than 5.0?
Yes. Linux source builds of SDK 3.x support GCC 4.8.5 and later, including GCC 4.8.5, 5.5.0, and 8.4.0. When integrating precompiled libraries, also match their runtime dependencies and C++ ABI.
Why can I not link the framework?
On Apple platforms, use .mm source files to call frameworks that mix Objective-C and C++. Configure the header and library search paths correctly.
How do I handle DNS: resolved timeout in older SDK versions?
SDK 3.0 and earlier may encounter resolution timeouts under high concurrency or when DNS is busy. Upgrade to SDK 3.1.x or later, and retry the request after a timeout. Newer versions add DNS timeout safeguards, but the runtime environment must still have a working DNS service.
Why does compilation or linking fail after I change _GLIBCXX_USE_CXX11_ABI?
The application, SDK, and related third-party libraries must use a compatible libstdc++ ABI. For source builds, check _GLIBCXX_USE_CXX11_ABI throughout the project, including CMakeLists.txt, config/linux.thirdparty.debug.cmake, and config/linux.thirdparty.release.cmake, and rebuild the affected dependencies. For precompiled libraries, select a package with a matching ABI.
How do the threading models of SDK 2.0 and SDK 3.x differ?
SDK 2.0 uses one thread per request and synchronous interfaces. SDK 3.x uses libevent to process events through asynchronous interfaces and supports concurrent requests.
How does the C++11 language standard relate to _GLIBCXX_USE_CXX11_ABI?
-std=c++11 selects the language standard. _GLIBCXX_USE_CXX11_ABI selects the libstdc++ ABI independently of that standard. The source project defaults to _GLIBCXX_USE_CXX11_ABI=0. To use the new ABI, align the build configurations of the SDK, application, and dependencies.
How do I handle nodename nor servname provided, or not known?
This error indicates a domain name resolution failure. Older SDK versions may encounter this issue on devices with IPv6 enabled. Upgrade to SDK 3.1.12 or later, and call setAddrInFamily("AF_INET") before startWorkThread to use IPv4 resolution.
How do I handle Network is unreachable after integration?
Check network connectivity from the runtime environment to the service endpoint. If local DNS interception causes incorrect libevent resolution results, use the option for your SDK version:
Earlier than 3.1.12: Replace
evdns_getaddrinfo()with the systemgetaddrinfo()and rebuild.3.1.12: Enable
add_definitions(-DNLS_USE_NATIVE_GETADDRINFO)inCMakeLists.txt.3.1.12 and later: Resolve the correct server IPv4 address outside the SDK and call
setDirectHost()beforestartWorkThread.3.1.13 and later: Call
setUseSysGetAddrInfo(true)beforestartWorkThreadto use system DNS resolution.
Which encoding must I use for synthesis text?
Synthesis text must use UTF-8 encoding. If text is garbled, synthesis fails, or Socket recv failed, errorCode: 0 appears, check the actual text encoding.
How do I check DNS configuration after DNS resolved timeout?
Check the nameserver entries in /etc/resolv.conf and ensure that the DNS servers are available. In an environment that can access public DNS, you can configure nameserver 114.114.114.114.