C++ SDK
This topic describes how to use the C++ software development kit (SDK) for Alibaba Cloud Intelligent Speech Interaction. It includes installation methods and code examples.
Prerequisites
Read the API reference. For more information, see API reference.
Obtain the AppKey for your project. For more information, see Create a project.
Obtain an Access Token. For more information, see Token overview.
Download and install
Download the SDK
You can obtain the SDK in one of the following two ways.
Method 1: Obtain the latest source code from GitHub. For more information about how to compile and run the code, see the following sections or the
readme.mdfile in the source code.git clone --depth 1 https://github.com/aliyun/alibabacloud-nls-cpp-sdkMethod 2: Download the required SDK package from the following table. The SDK source code package contains the original code. You must compile the code to generate the library files required for integration. The other packages for specific platforms contain the required library files and header files and do not require compilation.
Latest SDK package
Platform
MD5
SDK source code
4dbd8c7fc5581f5e6c46fd14bb68998e
Linux x86_64
f43507b82cf4ba1a9f902429dd780fac
NoteThe Linux-x86_64 version is compiled with gcc 8.4.0 and _GLIBCXX_USE_CXX11_ABI=0. You can recompile the source code package by following the instructions in the readme.md file.
Where:
alibabacloud-nls-cpp-sdk<version>-master_<github commit id>.zipis the SDK source code package.NlsCppSdk_<Platform>_<Version>_<github commit id>.tar.gzis the SDK package for the corresponding platform. For more information, see the readme.md file in the package.
SDK package files
scripts/build_linux.sh: An example compilation script for the Linux platform.CMakeLists.txt: TheCMakeLists.txtfile for an example code-based project for the Linux or Android platform.demo folder: Contains integration code examples in the SDK package. The following table uses the Linux platform as an example.
File name
Description
speechRecognizerDemo.cpp
Short sentence recognition example.
speechSynthesizerDemo.cpp
Speech synthesis example.
speechTranscriberDemo.cpp
Real-time speech recognition example.
flowingSynthesizerDemo.cpp
Streaming/Long-text-to-speech synthesis example.
fileTransferDemo.cpp
Audio file recognition example.
resource folder: Contains sample audio files for the Voice Service. You can use these files for functional testing.
File name
Description
test0.wav
test1.wav
test2.wav
test3.wav
Test audio files (16 kHz audio sampling rate, 16-bit audio bit depth).
include: Contains the SDK header files.File name
Description
nlsClient.h
SDK instance.
nlsEvent.h
Callback event descriptions.
nlsGlobal.h
Global SDK header file.
nlsToken.h
SDK Access Token instance.
iNlsRequest.h
Basic NLS request header file.
speechRecognizerRequest.h
Short sentence recognition.
speechSynthesizerRequest.h
Speech synthesis and long-text-to-speech synthesis.
speechTranscriberRequest.h
Real-time audio stream recognition.
flowingSynthesizerRequest.h
Streaming/Long-text-to-speech synthesis.
FileTrans.h
Audio file recognition.
lib: Contains the SDK library files.readme.md: The SDK instructions.release.log: The release notes.version: The version number.
Compile and run (Linux platform)
The following minimum tool versions are required:
CMake 3.0
Glibc 2.5
Gcc 4.8.5
Run the following scripts in the Linux terminal.
Go to the root directory of the SDK source code.
Generate the SDK library files and executable programs: srDemo (short sentence recognition), stDemo (real-time speech recognition), syDemo (speech synthesis), daDemo (speech interaction), and fsDemo (streaming or long-text-to-speech synthesis).
./scripts/build_linux.shView the example usage.
cd build/demo ./fsDemo
Key interfaces
Basic interfaces
NlsClient: The speech processing client. You can use this client for speech processing tasks such as short sentence recognition, real-time speech recognition, and speech synthesis. This client is thread-safe. We recommend that you create only one global instance.
Interface
Version enabled
Description
getInstance
2.x
Gets (creates) an
NlsClientinstance.setLogConfig
2.x
Sets the log file and storage path.
setDirectHost
3.x
Skips
DNSresolution and directly sets the server'sIPv4address. If you call this interface, call it beforestartWorkThread.setAddrInFamily
3.1.12
Sets the type of the socket address structure. The default value is
AF_INET, which returns onlyIPv4-related address information. Call this interface beforestartWorkThread.setUseSysGetAddrInfo
3.1.13
If the
DNSoflibeventdoes not meet requirements and cannot completeDNSresolution, call this interface to switch to the system's interface. Call this interface beforestartWorkThread.calculateUtf8Chars
3.1.14
Counts the number of characters in a text. You must pass text content with
UTF-8encoding. One Chinese character, one English letter, or one punctuation mark is counted as one character.setSyncCallTimeout
3.1.17
Sets the timeout period (in ms) for synchronous call mode. The default value is 0, which disables synchronous mode. In this mode,
start()returns only after all server-side results are received, andstop()returns only after theclose()callback is received. Call this interface beforestartWorkThread. Note: Enabling synchronous mode significantly reduces interface efficiency. Do not enable this mode in high-concurrency scenarios.setPreconnectedPool
3.3.0
Sets a pre-connection pool for each domain name URL. After each request is complete, the connection is internally maintained and reused. This reduces the connection time before each request and significantly lowers the first-packet latency. This setting conflicts with the long-connection mode and will disable it if it is already set. Do not use this mode for Tingwu scenarios. Call this interface before
startWorkThread.startWorkThread
3.x
Starts the worker threads. The default value is 1, which starts one thread. A value of -1 starts a number of threads equal to the number of CPU cores. In high-concurrency scenarios, we recommend that you set this to -1. This can be considered the initialization of the NlsClient instance and must be called.
getVersion
3.x
Gets the SDK version number.
releaseInstance
2.x
Destroys the
NlsClientobject instance.createFlowingSynthesizerRequest
3.2
Creates a long-text-to-speech synthesis object. It is thread-safe and supports high-concurrency requests.
releaseFlowingSynthesizerRequest
3.2
Destroys the long-text-to-speech synthesis object. Call this after the closed event of the current request.
NlsToken: Creates a Token object to request a token ID. When you request a new token, you must first obtain a valid timestamp. If the token expires, you must request a new one. Requesting a token multiple times within its validity period can return an incorrect token ID, which makes the token unusable.
Interface
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. Optional.
setServerVersion
Sets the API version. Optional.
setServerResourcePath
Sets the service path. Optional.
setRegionId
Sets the service region ID. Optional.
setAction
Sets the feature. Optional.
applyNlsToken
Requests a Token ID.
getToken
Gets the Token ID.
getExpireTime
Gets the token's expiration UNIX timestamp (in seconds).
getErrorMsg
Gets the error message.
NlsEvent: The event object. You can obtain the request status code, server-side response, failure information, and other details from this object.
Interface
Description
getStatusCode
Gets the status code. A normal status is 0 or 20000000. A failure corresponds to a specific error code.
getErrorMessage
In the
TaskFailedcallback, gets the error message for a failedNlsRequestoperation.getTaskId
Gets the
TaskIdof the task.getBinaryData
Gets the binary data returned from the cloud.
getAllResponse
Gets the full response from the cloud.
Long-text synthesis interfaces
The interface descriptions are based on the content of flowingSynthesizerRequest.h.
Interface | Version enabled | Description |
setOnSynthesisStarted | 3.2 | Sets the callback function for when long-text-to-speech synthesis starts. |
setOnSynthesisCompleted | 3.2 | Sets the callback function for when speech synthesis is completed. |
setOnChannelClosed | 2.x | Sets the callback function for when the channel is closed. |
setOnTaskFailed | 2.x | Sets the callback function for errors. |
setOnSentenceBegin | 3.2 | The callback function for when the server detects the beginning of a sentence. |
setOnSentenceEnd | 3.2 | The callback function for when the server detects the end of a sentence. It returns the full timestamp for that sentence. |
setOnBinaryDataReceived | 2.x | Sets the callback function for receiving binary audio data from speech synthesis. |
setOnSentenceSynthesis | 3.2 | The callback function that incrementally returns the speech synthesis result. It includes the latest audio and timestamp, full intra-sentence data, and incremental inter-sentence data. |
setOnMessage | 3.1.16 | Sets the callback function for the server-side |
setAppKey | 2.x | Sets the AppKey. |
setToken | 2.x | Token authentication. All requests must be authenticated using the |
setTokenExpirationTime | 3.3.0 | Sets the expiration time of the token. This is effective only when the pre-connection pool feature is enabled. It is used to refresh the nodes within the pre-connection pool. If not set, the expiration time is the timestamp when the token was added to the pool plus 12 hours. |
setUrl | 2.x | Sets the service URL. Optional. |
sendText | 3.2 | In a single streaming TTS session, a single synthesis request cannot exceed 5,000 characters, and the total cannot exceed 100,000 characters. One Chinese character, one English letter, one punctuation mark, or one space between sentences is counted as one character. |
setVoice | 2.x | Sets the voice. |
setVolume | 2.x | Sets the volume. |
setFormat | 2.x | Sets the audio data encoding format. The default is PCM. Supported formats include 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. |
setEnableSubtitle | 2.x | Specifies whether to enable the caption feature. |
setPayloadParam | 2.x | Sets parameters. The input parameter is a JSON-formatted string. |
setTimeout | 2.x | Sets the connection timeout period. The default is 5000 ms. |
setContextParam | 2.x | Sets custom user parameters. The input parameter is a JSON-formatted string. |
AppendHttpHeaderParam | 2.x | Sets custom |
setSendTimeout | 3.1.14 | Sets the sending timeout period. The default is 5000 ms. |
setEnableOnMessage | 3.1.16 | Enables the callback for messages returned by the server. |
setSingleRoundText | 3.3.0 | Sets the text for the current long-text-to-speech synthesis. |
getTaskId | 3.1.17 | Gets the |
start | 2.x | Starts the |
stop | 3.2 | Ends the synthesis task. You must wait for the synthesis to complete. You do not need to call this interface in long-text-to-speech synthesis. |
cancel | 2.x | Directly closes the speech synthesis process without confirming with the server. |
Code example
The example saves the synthesized audio to a file. To play the audio with high real-time performance, we recommend that you use streaming playback. This method plays audio data as it is received, which reduces latency because you do not need to wait for the synthesis to finish before you process the audio stream.
For the complete example, see the flowingSynthesizerRequest.cpp file in the demo folder of the SDK package.
Before you call the interface, you must configure the environment variables to read the access credentials. The environment variable names for the Intelligent Speech Interaction
AccessKey ID,AccessKey secret, andAppKeyareNLS_AK_ENV,NLS_SK_ENV, andNLS_APPKEY_ENV.
Status codes
C++ SDK status codes
Status code | Status message | Cause | Solution |
0 | Success | Success. | None. |
-10 | DefaultError | Default error. | Not currently in use. |
-11 | JsonParseFailed | Incorrect JSON format. | Check if the input JSON string is in the correct JSON format. |
-12 | JsonObjectError | Incorrect JSON object. | Try again. |
-13 | MallocFailed | Malloc failed. | Check if there is sufficient memory. |
-14 | ReallocFailed | Realloc failed. | Check if there is sufficient memory. |
-15 | InvalidInputParam | An invalid parameter was passed. | 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 | Number of invalid log files | Check the configured parameter for the number of log files. |
-100 | EncoderExistent | The NLS encoder already exists. | Try again. |
-101 | EncoderInexistent | The NLS encoder does not exist. | Re-initialize. |
-102 | OpusEncoderCreateFailed | Failed to create the Opus encoder. | Re-initialize. |
-103 | OggOpusEncoderCreateFailed | Failed to create the OggOpus encoder. | Re-initialize. |
-104 | InvalidEncoderType | Invalid encoder type. | OPUS may have been disabled at compile-time but is still being used. Or, check the |
-150 | EventClientEmpty | The main worker thread is a null pointer. It has been released. | Re-initialize by calling |
-151 | SelectThreadFailed | Failed to select a worker thread. It has not been initialized. | Re-initialize by calling |
-160 | StartCommandFailed | Failed to send the start command. | Try again. |
-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 started (received the started event callback) or has already been completed. |
-163 | InvalidOpusFrameSize | Invalid Opus frame size. The default is 640 bytes. | In OPU encoding mode, |
-164 | InvokeStopFailed | The request state machine is incorrect, causing stop to fail. | Check if the current request has not started (received the started event callback) or has already been completed. |
-165 | InvokeCancelFailed | The request state machine is incorrect, causing stop to fail. | Check if the current request has not started (received the started event callback) or has already been completed. |
-166 | InvokeStControlFailed | The request state machine is incorrect, causing stControl to fail. | Check if the current request has not started (received the started event callback) or has already been completed. |
-200 | NlsEventEmpty | The NLS event is empty. | For internal SDK use. The NlsEvent frame was 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 |
-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 | 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 request parameters. | 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 parameters passed for setting are empty. | Check if the passed parameters are 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 | DNS parsing detects the address. | For internal SDK use. Check if DNS is available in the current environment. |
-403 | ConnectFailed | Network connection failed. | Check if the network 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 network is available and try again. |
-407 | SslCtxEmpty | SSL_CTX is empty. | For internal SDK use. Check if the network is available and try again. |
-408 | SslNewFailed | SSL_new failed. | For internal SDK use. Check if the network is available and try again. |
-409 | SslSetFailed | Failed to set SSL parameters. | For internal SDK use. Check if the network is available and try again. |
-410 | SslConnectFailed | SSL_connect failed. | For internal SDK use. Check if the network is available and try again. |
-411 | SslWriteFailed | Failed to send data over SSL. | For internal SDK use. Check if the network is available and try again. |
-412 | SslReadSysError | A SYSCALL error occurred while receiving data over SSL. | For internal SDK use. Check if the network is available and try again. |
-413 | SslReadFailed | Failed to receive data over SSL. | For internal SDK use. Check if the network is available and try again. |
-414 | SocketFailed | Failed to create a socket. | For internal SDK use. Check if the network is available and try again. |
-415 | SetSocketoptFailed | Failed to set socket parameters. | For internal SDK use. Check if the network is available and try again. |
-416 | SocketConnectFailed | Failed to connect the socket. | For internal SDK use. Check if the network is available and try again. |
-417 | SocketWriteFailed | Failed to send data over the socket. | For internal SDK use. Check if the network is available and try again. |
-418 | SocketReadFailed | Failed to receive data from the socket. | For internal SDK use. Check if the network is available and try again. |
-430 | NlsReceiveFailed | Failed to receive NLS frame data. | For internal SDK use. Check if the network is available and try again. |
-431 | NlsReceiveEmpty | The received NLS frame data is empty. | For internal SDK use. Check if the network is available and try again. |
-432 | ReadFailed | Failed to receive data. | For internal SDK use. Check if the network is available and try again. |
-433 | NlsSendFailed | Failed to send NLS data. | For internal SDK use. Check if the network is available and try again. |
-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 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 (max cache for 16 kHz audio is 320000, for 8 kHz audio is 160000). Check if audio data is being sent too frequently or if too much data is being sent at once. |
-438 | EvutilSocketFalied | Failed to set evutil parameters. | For internal SDK use. Release the current request and try again. |
-439 | InvalidExitStatus | Invalid exit status. | Check if the current request has been canceled. |
-450 | InvalidAkId | The Alibaba Cloud account AccessKey ID is invalid. | Check if the Alibaba Cloud account AccessKey ID is empty. |
-451 | InvalidAkSecret | The Alibaba Cloud account AccessKey secret is invalid. | Check if the Alibaba Cloud account AccessKey secret is empty. |
-452 | InvalidAppKey | The project AppKey is invalid. | Check if the Alibaba Cloud project AppKey is empty. |
-453 | InvalidDomain | The domain is invalid. | Check if the input domain is empty. |
-454 | InvalidAction | The action is invalid. | Check if the input action is empty. |
-455 | InvalidServerVersion | The ServerVersion is invalid. | Check if the input ServerVersion is empty. |
-456 | InvalidServerResource | The ServerResource is invalid. | Check if the input ServerResource is empty. |
-457 | InvalidRegionId | The RegionId is invalid. | Check if the input Region ID is empty. |
-500 | InvalidFileLink | Invalid audio file link. | The audio file transcription file link is empty. |
-501 | ErrorStatusCode | Error status code. | Audio file transcription returned an error. See the error code for details. |
-502 | IconvOpenFailed | Failed to request a conversion descriptor. | UTF-8 to GBK conversion failed. |
-503 | IconvFailed | Encoding conversion failed. | UTF-8 to GBK conversion failed. |
-504 | ClientRequestFaild | Account client request failed. | Audio file transcription returned a failure. |
-999 | NlsMaxErrorCode | None. | None. |
Other status codes
Status code | Status message | Cause | Solution |
10000001 |
|
| Re-initialize. |
10000002 |
|
| Try again. |
| |||
10000003 |
| System error. | Handle the error based on the feedback from the system. |
10000004 |
|
| The input URL is empty. Enter a valid URL. |
10000005 |
|
| The input URL format is incorrect. Enter a valid URL. |
10000007 |
|
| JSON format is abnormal. Check the logs for the specific error point. |
10000008 |
|
| Network connection failed. Check if local DNS resolution is working and if the URL is valid. |
10000009 |
|
| Failed to connect to the cloud. Check the network and try again. |
10000010 |
| Out of memory. | Check if there is sufficient memory. |
10000015 |
|
| Network connection failed. Check if local DNS resolution is working and if the URL is valid. |
10000100 |
|
| Connection was rejected. Check your account, especially if the token has expired. |
10000101 |
|
| libevent timed out while sending an event. Check for time-consuming tasks in the callback, or if high concurrency is preventing timely> event processing. |
10000102 |
|
| libevent timed out while receiving an event. Check for time-consuming tasks in the callback, or if high concurrency is preventing timely> event processing. |
10000103 |
|
| Unknown libevent event. Try again. |
10000104 |
|
| Connection is in progress. Try again. |
10000105 |
|
| The pipe cannot handle the process. Try again. |
10000110 |
|
| Update the token. |
10000111 |
|
| Check the validity of the token. |
10000112 |
|
| You do not have permission to use this voice. |
10000113 |
|
| Check if your account has the required permissions, or if the number of concurrent connections is within the limit. |
10000120 |
|
| UTF-8 transcoding failed. This is often a system issue. Try again. |
20000000 |
| Success. |
Server-side response status codes
For more information about service status codes, see Service status codes.