C++ SDK
Use the C++ SDK to synthesize short text into audio and receive audio data and task status through callbacks.
Prerequisites and limitations
Activate the trial or commercial edition of speech synthesis.
Prepare an Alibaba Cloud AccessKey ID and AccessKey secret with the required permissions. For instructions, see Create an AccessKey pair.
The trial edition supports up to two concurrent requests. Use UTF-8 text with no more than 300 characters. For parameters, voices, and service endpoints, see 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 | A demo for short sentence recognition. |
speechSynthesizerDemo.cpp | A demo for speech synthesis. |
speechTranscriberDemo.cpp | A demo for real-time speech recognition. |
fileTransferDemo.cpp | A demo for audio file recognition. |
resource
Contains sample audio at 16 kHz with a 16-bit sample depth:
File name | Description |
| Test audio files with a 16 kHz audio sampling rate and 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-to-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 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 = "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(ShortTts);
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 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 name | Version enabled | Feature description |
getInstance | 2.x | Gets (creates) an NlsClient instance. |
setLogConfig | 2.x | Sets the log file and storage path. |
setDirectHost | 3.x | Skips domain name system (DNS) resolution and directly sets the server IPv4 address. If you call this interface, call it before startWorkThread. |
setAddrInFamily | 3.1.12 | Sets the address family for the socket address structure. The default value is AF_INET, which returns only IPv4-related address information. This interface must be called before startWorkThread. |
setUseSysGetAddrInfo | 3.1.13 | If the libevent DNS cannot meet your needs and fails to complete DNS resolution, you can call this interface to switch to the system's interface. This interface must be called before startWorkThread. |
calculateUtf8Chars | 3.1.14 | Counts the number of characters in the text. You must pass UTF-8 encoded text. 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 | Gets the SDK version number. |
releaseInstance | 2.x | Destroys the NlsClient object instance. |
| createSynthesizerRequest | 2.x | Creates a synthesis request. Use |
releaseSynthesizerRequest | 2.x | Destroys the speech synthesis object. This must be called after the closed event of the current request. |
NlsToken
NlsToken requests an NLS token and provides its expiration time.
Interface name | Feature description |
setAccessKeyId | Sets the AccessKey ID of your Alibaba Cloud account. |
setKeySecret | Sets the AccessKey secret of your Alibaba Cloud account. |
setDomain | Sets the domain name. This parameter is optional. |
setServerVersion | Sets the API version. This parameter is optional. |
setServerResourcePath | Sets the service path. This parameter is optional. |
setRegionId | Sets the service region ID. Optional. |
setAction | Sets the feature. This parameter is optional. |
applyNlsToken | Requests a token ID. |
getToken | Gets the token ID. |
getExpireTime | Gets the token's expiration timestamp in seconds. |
getErrorMsg | Gets the error message. |
NlsEvent
NlsEvent provides request status, task IDs, audio data, and server responses.
Interface name | Feature description |
getStatusCode | Gets the status code. A value of 0 or 20000000 indicates success. A failure returns a corresponding error code. |
getErrorMessage | In the TaskFailed callback, gets the error message for a failure that occurs during an NlsRequest operation. |
getTaskId | Gets the task ID. |
getBinaryData | Gets 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 Speech synthesis API reference.
Interface name | Version enabled | Feature description |
setOnSynthesisCompleted | 2.x | Sets the callback function for when speech synthesis is complete. |
setOnChannelClosed | 2.x | Sets the callback function for when the channel is closed. |
setOnTaskFailed | 2.x | Sets the callback function for errors. |
setOnBinaryDataReceived | 2.x | Sets 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 | Sets the callback function for server response messages. All callback output is from this callback and must be parsed by the user. This parameter is optional. After setting it, you must call setEnableOnMessage to enable it. |
setAppKey | 2.x | Sets the AppKey. |
setToken | 2.x | Sets the NLS token for request authentication. |
setUrl | 2.x | Sets the service URL. This parameter is optional. |
setText | 2.x | Sets the UTF-8 text to synthesize. |
setVoice | 2.x | Sets the voice. |
setVolume | 2.x | Sets the volume. |
setFormat | 2.x | Sets the output audio encoding format. The default value is PCM. Supported formats are PCM, WAV, and MP3. |
setSampleRate | 2.x | Sets the audio sampling rate. |
setSpeechRate | 2.x | Sets the speech rate. |
setPitchRate | 2.x | Sets the pitch rate. |
setMethod | 2.x | Sets the synthesis method. The default value is 0.
|
setEnableSubtitle | 2.x | Indicates whether the caption feature is enabled. |
setPayloadParam | 2.x | Sets 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 | Sets custom user parameters. The input parameter is a JSON-formatted string. |
AppendHttpHeaderParam | 2.x | Sets custom HTTP header parameters for the WebSocket phase. |
setSendTimeout | 3.1.14 | Sets the sending timeout period. The default value is 5000 ms. |
setEnableOnMessage | 3.1.16 | Enables the callback for messages returned from the server. |
getTaskId | 3.1.17 | Gets the task ID of the current request. |
start | 2.x | Starts the SpeechSynthesizerRequest. |
cancel | 2.x | Immediately closes the speech synthesis process without confirming the shutdown 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 currently in use. |
-11 | JsonParseFailed | Invalid JSON format | Check whether the input JSON string is in the correct JSON format. |
-12 | JsonObjectError | Invalid JSON object | Retry the operation. |
-13 | MallocFailed | Malloc failed | Check if there is sufficient memory. |
-14 | ReallocFailed | Realloc failed | Check if there is sufficient memory. |
-15 | InvalidInputParam | Invalid input parameter | Not currently 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 number of log files parameter. |
-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 reinitialize. |
-103 | OggOpusEncoderCreateFailed | Failed to create the OggOpus encoder. | We recommend that you reinitialize. |
-104 | InvalidEncoderType | Invalid encoder type | OPUS may have been disabled at compile-time but is being used, or check the 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. 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 if 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 if the current request has been started (that is, the started event callback has been received) or has already been completed. |
-163 | InvalidOpusFrameSize | Invalid Opus frame size. The default is 640 bytes. | In OPU encoding mode, sendAudio accepts only one frame of 640 bytes of data. |
-164 | InvokeStopFailed | The request state machine is incorrect, causing stop to fail. | Check if the current request is either not yet started (the 'started' event callback has not been received) or already complete. |
-165 | InvokeCancelFailed | The request state machine is incorrect, causing cancel to fail. | Check whether the 'started' event callback has not been received or the request is already complete. |
-166 | InvokeStControlFailed | The request state machine is incorrect, causing stControl to fail. | Check if the 'started' event callback has not been received, or if the request 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 currently in use. |
-251 | InvalidWorkStatus | Invalid working status | For internal SDK use. The internal status of the current request is invalid. |
-252 | InvalidNodeQueue | Invalid NodeQueue in workThread. | For internal SDK use. The current request to be run is invalid. Release the current request and retry. |
-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 retry. |
-302 | InvalidRequest | Invalid request | For internal SDK use. The current request has been released. Release the current request and retry. |
-303 | SetParamsEmpty | The input parameter is empty. | Check if 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 | Bad HTTP 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 due to 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 retry. |
-401 | InvaildNodeStatus | The node status is invalid. | For internal SDK use. Release the current request and retry. |
-402 | GetAddrinfoFailed | Detecting addresses using DNS parsing | For internal SDK use. Check if DNS is available in the current environment. |
-403 | ConnectFailed | Network connection failed. | Check if the current network environment is available. |
-404 | InvalidDnsSource | No DNS on the current device. | For internal SDK use. Check if DNS is available in the current environment. |
-405 | ParseUrlFailed | Invalid URL | Check if the configured URL is valid. |
-406 | SslHandshakeFailed | SSL handshake failed. | For internal SDK use. Check if the current network environment is available and retry. |
-407 | SslCtxEmpty | SSL_CTX is empty. | For internal SDK use. Check if the current network environment is available and retry. |
-408 | SslNewFailed | SSL_new failed. | For internal SDK use. Check if the current network environment is available and retry. |
-409 | SslSetFailed | Failed to set SSL parameters. | For internal SDK use. Check if the current network environment is available and retry. |
-410 | SslConnectFailed | SSL_connect failed. | For internal SDK use. Check if the current network environment is available and retry. |
-411 | SslWriteFailed | Failed to send data over SSL. | For internal SDK use. Check if the current network environment is available and retry. |
-412 | SslReadSysError | SYSCALL error received when reading data over SSL. | For internal SDK use. Check if the current network environment is available and retry. |
-413 | SslReadFailed | Failed to read data over SSL. | For internal SDK use. Check if the current network environment is available and retry. |
-414 | SocketFailed | Failed to create a socket. | For internal SDK use. Check if the current network environment is available and retry. |
-415 | SetSocketoptFailed | Failed to set socket parameters. | For internal SDK use. Check if the current network environment is available and retry. |
-416 | SocketConnectFailed | Failed to establish a socket connection. | For internal SDK use. Check if the current network environment is available and retry. |
-417 | SocketWriteFailed | Failed to send data over the socket. | For internal SDK use. Check if the current network environment is available and retry. |
-418 | SocketReadFailed | Failed to read data from the socket. | For internal SDK use. Check if the current network environment is available and retry. |
-430 | NlsReceiveFailed | Failed to receive NLS frame data. | For internal SDK use. Check if the current network environment is available and retry. |
-431 | NlsReceiveEmpty | Received NLS frame data is empty. | For internal SDK use. Check if the current network environment is available and retry. |
-432 | ReadFailed | Failed to receive data. | For internal SDK use. Check if the current network environment is available and retry. |
-433 | NlsSendFailed | Failed to send NLS data. | For internal SDK use. Check if the current network environment is available and retry. |
-434 | NewOutputBufferFailed | Failed to create a buffer. | For internal SDK use. Check if there is sufficient memory. |
-435 | NlsEncodingFailed | Audio encoding failed. | For internal SDK use. Release the current request and retry. |
-436 | EventEmpty | The event is empty. | For internal SDK use. Release the current request and retry. |
-437 | EvbufferTooMuch | Too much data in evbuffer. | For internal SDK use. The send data buffer is full. The maximum buffer size is 320,000 for 16 kHz audio and 160,000 for 8 kHz audio. Check if you are sending audio data too frequently or sending too much data at once. |
-438 | EvutilSocketFailed | Failed to set evutil parameters. | For internal SDK use. Release the current request and retry. |
-439 | InvalidExitStatus | Invalid exit status | Check if you have already canceled the current request. |
-450 | InvalidAkId | Invalid AccessKey ID for the Alibaba Cloud account. | Check if the AccessKey ID for the Alibaba Cloud account is empty. |
-451 | InvalidAkSecret | Invalid AccessKey secret for the Alibaba Cloud account. | Check if the AccessKey secret for the Alibaba Cloud account is empty. |
-452 | InvalidAppKey | Invalid project AppKey. | Check if the project AppKey for Alibaba Cloud is empty. |
-453 | InvalidDomain | Invalid domain | Check if the input domain is empty. |
-454 | InvalidAction | Invalid action | Check if the input action is empty. |
-455 | InvalidServerVersion | Invalid ServerVersion | Check if the input ServerVersion is empty. |
-456 | InvalidServerResource | Invalid ServerResource | Check if the input ServerResource is empty. |
-457 | InvalidRegionId | Invalid RegionId | Check if the input RegionId is empty. |
-500 | InvalidFileLink | Invalid audio file link | The audio file link for audio file transcription is empty. |
-501 | ErrorStatusCode | Error status code | An error was returned for audio file transcription. For more information, see the error code. |
-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 system feedback. |
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 format is incorrect. Enter a valid URL. |
10000007 | JsonStringParseFailed | JSON: Json parse failed. | JSON format is abnormal. Check the logs for specific error details. |
10000008 | UnknownWsHeadType | WEBSOCKET: unkown head type. | Network connection failed. Check if the local DNS resolution and URL are valid. |
10000009 | HttpConnectFailed | HTTP: connect failed. | Failed to connect to the cloud. Check your network and retry. |
10000010 | MemNotEnough | Out of memory. | Check if there is sufficient memory. |
10000015 | SysConnectFailed | connect failed. | Network connection failed. Check if the local DNS resolution and URL are valid. |
10000100 | HttpGotBadStatusWith403 | Got bad status host=xxxxx line=HTTP/1.1 403 Forbidden | Connection was rejected. Check your account, especially if the token has expired. |
10000101 | EvSendTimeout | Send timeout. socket error: | libevent timed out when sending an event. Check for time-consuming tasks in the callback, or if high concurrency is preventing events from being processed promptly. |
10000102 | EvRecvTimeout | Recv timeout. socket error: | libevent timed out when receiving an event. Check for time-consuming tasks in the callback, or if high concurrency is preventing events from being processed promptly. |
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 handle the request. 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 if your account has the required permissions or if the number of concurrent requests 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
Why does the service report appkey not set after I configure it?
40000003 indicates an invalid request parameter. Check whether the supplied appkey is empty and whether parameters such as voice and url are correct.
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.