C# SDK

Updated at:

This topic describes how to use the C# software development kit (SDK) for Alibaba Cloud Voice Service. It includes installation methods and code samples.

Download the SDK

Note
  • Current version: 3.1.17. This version is based on C++ SDK API 3.1.x. Release date: August 28, 2023.

  • This SDK is a C# wrapper for the underlying C++ SDK and supports only the Windows platform.

  • Before you use the SDK, read the API reference. For more information, see the API reference.

You can obtain the SDK using one of the following methods.

  • Method 1: Obtain the latest source code from GitHub. For detailed compilation and execution instructions, see the following sections or the readme.md file in the source code.

    git clone --depth 1 https://github.com/aliyun/alibabacloud-nls-cpp-sdk
  • Method 2: Download the required SDK package from the table below. The SDK source code package contains the original code that you must compile to generate the library files required for integration. The other SDK packages for specific platforms contain the required library files and header files and do not need to be compiled.

    Latest SDK package

    Platform

    MD5

    alibabacloud-nls-cpp-sdk3.1.17-master_fd7c7d8.zip

    SDK source code

    8beeaad832d4b249464f4338429c3b15

    NlsCsharpSdk_Windows_3.1.17_fd7c7d8.zip

    Windows

    81fdd1579e103d8c93b4dab98ee0f71c

    Where:

    • alibabacloud-nls-cpp-sdk<version>-master_<github commit id>.zip is the SDK source code package.

    • NlsCsharpSdk_Windows_<version_number>_<github commit id>.zip is the SDK package required for development on the Windows platform. For more information, see the readme.md file in the package.

Compile and run on Windows

You can use the pre-compiled library NlsCsharpSdk_Windows_<version>_<github commit id>.zip for integration. To compile the code, download and decompress alibabacloud-nls-cpp-sdk<version>-master_<github commit id>.zip to your local machine, or obtain the latest code from GitHub. Then, follow the compilation steps in the readme.md file.

Key interfaces

using nlsCsharpSdk;
  • Basic interfaces

    • NlsClient: A voice processing client used for short sentence recognition, real-time speech recognition, and speech synthesis. The client is thread-safe, and you should create only one global instance.

      Interface

      Enable Versioning

      Description

      SetLogConfig

      3.1.9

      Sets the log file and storage path. Call this interface as early as possible to record more detailed information.

      GetVersion

      3.1.9

      Gets the SDK version number.

      CreateNlsToken

      3.1.9

      Creates a token object to request a TokenId. For more information, see the NlsToken section below.

      ReleaseNlsToken

      3.1.9

      Destroys the NlsToken object created by CreateNlsToken.

      SetDirectHost

      3.1.16

      Skips DNS resolution and directly sets the server IP address. If you call this interface, you must call it before StartWorkThread.

      StartWorkThread

      3.1.9

      Starts 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. For high-concurrency scenarios, set this parameter to 4. This interface also initializes the NlsClient.

      ReleaseInstance

      3.1.9

      Destroys the NlsClient object instance and releases the NLS SDK. Call this operation after all requests are destroyed.

      CreateNlsToken

      3.1.9

      Creates a token object to request a TokenId. For more information, see the NlsToken description below.

      ReleaseNlsToken

      3.1.9

      Destroys the token acquisition object.

      CreateSynthesizerRequest

      3.1.9

      Creates a speech synthesis object. It is thread-safe and supports high-concurrency requests. Use input parameters to control short-text or long-text mode. For more information, see API reference.

      ReleaseSynthesizerRequest

      3.1.9

      Destroys the speech synthesis object. Call this interface after the closed event of the current request.

    • NlsToken: Creates a token object to request a TokenId. To 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 causes a TokenId error and 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.

      ApplyNlsToken

      Requests a TokenId. Within its validity period, this TokenId is valid for all voice requests made with the associated AccessKey ID. You do not need to request a new TokenId for each voice request.

      GetToken

      Gets the TokenId.

      GetExpireTime

      Gets the UNIX timestamp (in seconds) when the token expires.

      GetErrorMsg

      Gets the error message if the TokenId request fails.

    • NlsEvent: This is the NLS_EVENT_STRUCT event object, which is returned through CallbackDelegate. You can use this object to obtain the request status code, server-side response, and failure information.

      Interface

      Description

      statusCode

      Gets the status code. A value of 0 or 20000000 indicates success. Otherwise, it is an error code.

      taskId

      Gets the task ID.

      msg

      Gets the response from the server. Use it to obtain event information from callbacks such as Started, Closed, TaskFailed, Completed, and MetaInfo.

      result

      Gets the recognition result from the server. For speech synthesis, this parameter is the same as `msg`.

  • Identification

    SpeechSynthesizerRequest: A speech synthesis request object used for speech synthesis and long-text speech synthesis.

    Interface

    Description

    SetOnSynthesisCompleted

    Sets the callback function for when speech synthesis is completed.

    SetOnChannelClosed

    Sets the callback function for when the channel is closed.

    SetOnTaskFailed

    Sets the callback function for errors.

    SetOnBinaryDataReceived

    Sets the callback function for receiving binary audio data from speech synthesis.

    SetOnMetaInfo

    Sets the callback function for receiving log information corresponding to the text.

    SetAppKey

    Sets the AppKey.

    SetToken

    Authenticates the request with a token. All requests must be authenticated by the SetToken method.

    SetUrl

    Sets the service URL. If you do not set this, the service in the public cloud Shanghai region is called by default.

    SetText

    Sets the text to be synthesized. The text must be in UTF-8 format. In short-text speech synthesis mode, you can synthesize up to 300 characters at a time. A Chinese character, an English letter, or a punctuation mark is counted as one character. Text exceeding 300 characters will cause an error or be truncated. For text longer than 300 characters, consider using long-text speech synthesis. For more information, see API reference.

    SetVoice

    Sets the voice. For more information, see API reference.

    SetVolume

    Sets the volume. This is an optional parameter. The range is 0 to 100. The default value is 50.

    SetFormat

    Sets the output audio encoding format.

    SetSampleRate

    Sets the audio sample rate.

    SetSpeechRate

    Sets the speech rate. This is an optional parameter. The range is -500 to 500. The default value is 0.

    SetPitchRate

    Sets the pitch. This is an optional parameter. The range is -500 to 500. The default value is 0.

    SetEnableSubtitle

    Enables or disables the caption feature. If enabled, you can obtain detailed synthesis information, such as the timestamp for each character, which is returned through the MetaInfo callback.

    SetMethod

    Specifies the synthesis method. The default value is 0.

    • 0: Statistical parametric synthesis. This method synthesizes speech based on statistical parameters. It offers a wide range of adaptable prosodic features, a low synthesizer bit rate, low resource usage, and high performance with moderate sound quality.

    • 1: Concatenative synthesis. This method synthesizes speech by learning from and combining segments from a high-quality voice database. It uses more resources but produces better sound quality that is closer to natural human speech. However, it is less stable than parametric synthesis.

    SetTimeout

    Sets the socket reception timeout period.

    SetPayloadParam

    Sets parameters. The input parameter is a JSON string. For example, to specify an acoustic model: "{\"model\":\"test-regression-model\"}").

    SetContextParam

    Sets custom user parameters. The input parameter is a JSON string.

    SetOutputFormat

    Sets the encoding format for the output text. The default format on Windows is GBK. For non-Chinese languages, set this to UTF-8 to avoid garbled characters.

    GetOutputFormat

    Gets the encoding format of the output text. The default format on Windows is GBK.

    AppendHttpHeaderParam

    Sets custom HTTP header parameters for the WebSocket phase.

    Start

    Asynchronous interface. Starts the SpeechSynthesizerRequest.

    Cancel

    Closes the speech synthesis process directly without confirming with the server.

SDK 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 correct JSON format.

-12

JsonObjectError

Invalid JSON object

Retry the operation.

-13

MallocFailed

Malloc failed

Check if you have enough memory.

-14

ReallocFailed

Realloc failed

Check if you have enough memory.

-15

InvalidInputParam

Invalid input parameter

Not in use.

-50

InvalidLogLevel

Invalid log level

Check the log level settings.

-51

InvalidLogFileSize

Invalid log file size

Check the log file size parameter.

-52

InvalidLogFileNum

Invalid number of log files

Check the 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 reinitializing.

-102

OpusEncoderCreateFailed

Failed to create the Opus encoder.

We recommend re-initializing.

-103

OggOpusEncoderCreateFailed

Failed to create the OggOpus encoder.

We recommend re-initializing.

-150

EventClientEmpty

The main worker thread is a null pointer and has been released.

Re-initialize by calling startWorkThread().

-151

SelectThreadFailed

Failed to select a worker thread. The thread is not initialized.

Re-initialize 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 been completed.

-162

InvokeSendAudioFailed

The request state machine is incorrect, causing sendAudio to fail.

Check whether the current request has started (the started event callback is received) or has been completed.

-163

InvalidOpusFrameSize

Invalid Opus frame size. The default size 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.

Check whether the current request has not yet started (that is, a `started` event callback has not been received) or is already complete.

-165

InvokeCancelFailed

The request state machine is incorrect, causing cancel to fail.

You can check whether the current request has not started (i.e., a started event callback has not been received) or is already complete.

-166

InvokeStControlFailed

The request state machine is incorrect, causing stControl to fail.

You can check whether the current request has not started (that is, a started event callback has not been received) or is 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 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 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 status is invalid.

For internal SDK use. Release the current request and try again.

-402

GetAddrinfoFailed

Detection via DNS parsing

For internal SDK use. Check whether DNS is available in the current environment.

-403

ConnectFailed

Network connection failed.

Check whether your network 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 URL is valid.

-406

SslHandshakeFailed

SSL handshake failed.

For internal SDK use. Check whether your network is available and try again.

-407

SslCtxEmpty

SSL_CTX is empty.

For internal SDK use. Check whether your network is available and try again.

-408

SslNewFailed

SSL_new failed.

For internal SDK use. Check whether your network is available and try again.

-409

SslSetFailed

Failed to set SSL parameters.

For internal SDK use. Check whether your network is available and try again.

-410

SslConnectFailed

SSL_connect failed.

For internal SDK use. Check whether your network is available and try again.

-411

SslWriteFailed

Failed to send data over SSL.

For internal SDK use. Check whether your network is available and try again.

-412

SslReadSysError

A SYSCALL error occurred while receiving data over SSL.

For internal SDK use. Check whether your network is available and try again.

-413

SslReadFailed

Failed to receive data over SSL.

For internal SDK use. Check whether your network is available and try again.

-414

SocketFailed

Failed to create a socket.

For internal SDK use. Check whether your network is available and try again.

-415

SetSocketoptFailed

Failed to set socket parameters.

For internal SDK use. Check whether your network is available and try again.

-416

SocketConnectFailed

Failed to establish a socket connection.

For internal SDK use. Check whether your network is available and try again.

-417

SocketWriteFailed

Failed to send data over the socket.

For internal SDK use. Check whether your network is available and try again.

-418

SocketReadFailed

Failed to receive data from the socket.

For internal SDK use. Check whether your network is available and try again.

-430

NlsReceiveFailed

Failed to receive NLS frame data.

For internal SDK use. Check whether your network is available and try again.

-431

NlsReceiveEmpty

The received NLS frame data is empty.

For internal SDK use. Check whether your network is available and try again.

-432

ReadFailed

Failed to receive data.

For internal SDK use. Check whether your network is available and try again.

-433

NlsSendFailed

Failed to send NLS data.

For internal SDK use. Check whether your network is available and try again.

-434

NewOutputBufferFailed

Failed to create a buffer.

For internal SDK use. Check if you have enough 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 (the maximum cache 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 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 AppKey for the Alibaba Cloud project 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 link to the audio file 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

The account client request failed.

Audio file transcription failed.

-999

NlsMaxErrorCode

Other status codes

Status message

Cause

Solution

10000001

NewSslCtxFailed

SSL: couldn't create a context!

We recommend re-initializing.

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.

Invalid JSON format. Check the logs for specific error details.

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 server. Check your network and try again.

10000010

MemNotEnough

Out of memory.

Check if you have enough memory.

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 and whether the token has expired.

10000101

EvSendTimeout

Send timeout. socket error:

libevent timed out while sending an event. Check for time-consuming tasks in the callback or high concurrency that prevents timely event processing.

10000102

EvRecvTimeout

Recv timeout. socket error:

libevent timed out while receiving an event. Check for time-consuming tasks in the callback or high concurrency that 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 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

Server response status codes

For information about service status codes, see Service status codes.

Code samples

  • The audio file used in the sample has a sample rate of 16000 Hz, and the model is set to the Universal model in the console. If you use other audio files, you must set the model to one that supports the audio scenario. For more information about model settings, see Manage projects.

  • The sample uses the default public URL for the built-in speech synthesis service. If you use an Alibaba Cloud ECS instance in the China (Shanghai) region and need to use an internal URL, set the internal URL in the SpeechSynthesizerRequest object.

    SpeechSynthesizerRequest syPtr;
    syPtr.SetUrl(syPtr, "ws://nls-gateway.cn-shanghai-internal.aliyuncs.com/ws/v1")
  • The following code shows a brief sample. For the complete sample, see the nlsCsharpSdkDemo.cs file in the demo directory of the SDK package.

    using System;
    using System.IO;
    using System.Threading;
    using System.Windows.Forms;
    using nlsCsharpSdk;
    
    namespace nlsCsharpSdkDemo
    {
        public partial class nlsCsharpSdkDemo : Form
        {
            private NlsClient nlsClient;
            private SpeechSynthesizerRequest syPtr;
            private NlsToken tokenPtr;
            private UInt64 expireTime;
    
            private string appKey;
            private string akId;
            private string akSecret;
            private string token;
            private string url;
    
            static bool running;
            static string cur_nls_result;
    
            static string cur_sy_completed;
            static string cur_sy_closed;
    
            private void FlushLab()
            {
                while (running)
                {
                    if (cur_nls_result != null && cur_nls_result.Length > 0)
                    {
                        nlsResult.Text = cur_nls_result;
                    }
    
                    if (cur_st_result != null && cur_st_result.Length > 0)
                    {
                        stResult.Text = cur_st_result;
                    }
                    if (cur_st_completed != null && cur_st_completed.Length > 0)
                    {
                        stCompleted.Text = cur_st_completed;
                    }
                    if (cur_st_closed != null && cur_st_closed.Length > 0)
                    {
                        stClosed.Text = cur_st_closed;
                    }
    
                    if (cur_sr_result != null && cur_sr_result.Length > 0)
                    {
                        srResult.Text = cur_sr_result;
                    }
                    if (cur_sr_completed != null && cur_sr_completed.Length > 0)
                    {
                        srCompleted.Text = cur_sr_completed;
                    }
                    if (cur_sr_closed != null && cur_sr_closed.Length > 0)
                    {
                        srClosed.Text = cur_sr_closed;
                    }
    
                    if (cur_sy_completed != null && cur_sy_completed.Length > 0)
                    {
                        syCompleted.Text = cur_sy_completed;
                    }
                    if (cur_sy_closed != null && cur_sy_closed.Length > 0)
                    {
                        syClosed.Text = cur_sy_closed;
                    }
                    Thread.Sleep(200);
                }
            }
    
            public nlsCsharpSdkDemo()
            {
                InitializeComponent();
                System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;// Set this property to false.
    
                nlsClient = new NlsClient();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                // Enable the logging system. Store logs named nlsLog.log at the Debug level. The logs are rotated with 10 files, each 400 MB in size.
                int ret = nlsClient.SetLogConfig("nlsLog", LogLevel.LogDebug, 400, 10);
                if (ret == 0)
                    nlsResult.Text = "OpenLog Success";
                else
                    nlsResult.Text = "OpenLog Failed";
            }
    
            private void button1_Click_1(object sender, EventArgs e)
            {
                string version = nlsClient.GetVersion();
                nlsResult.Text = version;
            }
    
            private void button1_Click_2(object sender, EventArgs e)
            {
                // A value of -1 starts a number of event pools equal to the number of CPU cores for internal event processing.
                // For single-channel calls, we recommend that you set the parameter to 1 to start a single event pool.
                // For high concurrency (hundreds of channels), we recommend that you set the parameter to a value from 4 to the number of CPU cores. A larger value reduces processing latency but increases CPU usage.
                nlsClient.StartWorkThread(1);
                nlsResult.Text = "StartWorkThread and init NLS success.";
                running = true;
                Thread t = new Thread(FlushLab);
                t.Start();
            }
    
            private void button1_Click_3(object sender, EventArgs e)
            {
                nlsClient.ReleaseInstance();
                nlsResult.Text = "Release NLS success.";
            }
    
            #region Info
            private void textBox1_TextChanged(object sender, EventArgs e)
            {
                akId = tAkId.Text;
            }
    
            private void tAppKey_TextChanged(object sender, EventArgs e)
            {
                appKey = tAppKey.Text;
            }
    
            private void tAkSecret_TextChanged(object sender, EventArgs e)
            {
                akSecret = tAkSecret.Text;
            }
    
            private void tToken_TextChanged(object sender, EventArgs e)
            {
                token = tToken.Text;
            }
    
            private void tUrl_TextChanged(object sender, EventArgs e)
            {
                url = tUrl.Text;
            }
            #endregion
    
            #region TokenButton
            // create token
            private void button3_Click_1(object sender, EventArgs e)
            {
                int ret = -1;
                tokenPtr = nlsClient.CreateNlsToken();
                if (tokenPtr.native_token != IntPtr.Zero)
                {
                    if (akId != null && akSecret != null & akId.Length > 0 && akSecret.Length > 0)
                    {
                        tokenPtr.SetAccessKeyId(tokenPtr, akId);
                        tokenPtr.SetKeySecret(tokenPtr, akSecret);
    
                        ret = tokenPtr.ApplyNlsToken(tokenPtr);
                        if (ret < 0)
                        {
                            System.Diagnostics.Debug.WriteLine("ApplyNlsToken failed");
                            nlsResult.Text = tokenPtr.GetErrorMsg(tokenPtr);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("ApplyNlsToken success");
                            token = tokenPtr.GetToken(tokenPtr);
                            tToken.Text = token;
                            expireTime = tokenPtr.GetExpireTime(tokenPtr);
                            nlsResult.Text = "ExpireTime:" + expireTime.ToString();
                        }
                    }
                    else
                    {
                        nlsResult.Text = "CreateToken Failed, akId or Secret is null";
                    }
                }
                else
                {
                    nlsResult.Text = "CreateToken Failed";
                }
            }
    
            // release token
            private void button4_Click(object sender, EventArgs e)
            {
                if (tokenPtr.native_token != IntPtr.Zero)
                {
                    nlsClient.ReleaseNlsToken(tokenPtr);
                    tokenPtr.native_token = IntPtr.Zero;
                    nlsResult.Text = "ReleaseNlsToken Success";
                }
                else
                {
                    nlsResult.Text = "ReleaseNlsToken is nullptr";
                }
            }
            #endregion
    
            #region SynthesizerCallback
            private CallbackDelegate DemoOnBinaryDataReceived =
                (ref NLS_EVENT_STRUCT e,ref string uuid) =>
                {
                    System.Diagnostics.Debug.WriteLine("DemoOnBinaryDataReceived uuid = {0}", uuid);
                    System.Diagnostics.Debug.WriteLine("DemoOnBinaryDataReceived taskId = {0}", e.taskId);
                    System.Diagnostics.Debug.WriteLine("DemoOnBinaryDataReceived dataSize = {0}", e.binaryDataSize);
                    //cur_sy_completed = e.taskId + ", binaryDataSize : " + e.binaryDataSize;
                };
            private CallbackDelegate DemoOnSynthesisClosed =
                (ref NLS_EVENT_STRUCT e, ref string uuid) =>
                {
                    System.Diagnostics.Debug.WriteLine("DemoOnSynthesisClosed user uuid = {0}", uuid);
                    string msg = System.Text.Encoding.Default.GetString(e.msg).TrimEnd('\0');
                    System.Diagnostics.Debug.WriteLine("DemoOnSynthesisClosed msg = {0}", msg);
                    cur_sy_closed = "msg : " + msg;
                };
            private CallbackDelegate DemoOnSynthesisTaskFailed =
                (ref NLS_EVENT_STRUCT e, ref string uuid) =>
                {
                    System.Diagnostics.Debug.WriteLine("DemoOnSynthesisTaskFailed user uuid = {0}", uuid);
                    string msg = System.Text.Encoding.Default.GetString(e.msg).TrimEnd('\0');
                    System.Diagnostics.Debug.WriteLine("DemoOnSynthesisTaskFailed msg = {0}", msg);
                    cur_sy_completed = "msg : " + msg;
                };
            private CallbackDelegate DemoOnSynthesisCompleted =
                (ref NLS_EVENT_STRUCT e, ref string uuid) =>
                {
                    System.Diagnostics.Debug.WriteLine("DemoOnSynthesisCompleted user uuid = {0}", uuid);
                    string msg = System.Text.Encoding.Default.GetString(e.msg).TrimEnd('\0');
                    System.Diagnostics.Debug.WriteLine("DemoOnSynthesisCompleted msg = {0}", msg);
                    cur_sy_completed = "result : " + msg;
                };
            private CallbackDelegate DemoOnMetaInfo =
                (ref NLS_EVENT_STRUCT e, ref string uuid) =>
                {
                    System.Diagnostics.Debug.WriteLine("DemoOnMetaInfo user uuid = {0}", uuid);
                    // If the recognized text is not Chinese, set the format to UTF-8 and decode using UTF-8 to prevent garbled characters.
                    // string msg = System.Text.Encoding.UTF8.GetString(e.msg).TrimEnd('\0');
                    string msg = System.Text.Encoding.Default.GetString(e.msg).TrimEnd('\0');
                    System.Diagnostics.Debug.WriteLine("DemoOnMetaInfo msg = {0}", msg);
                    cur_sy_completed = "metaInfo : " + msg;
                };
            #endregion
    
            // create synthesizer
            private void button12_Click(object sender, EventArgs e)
            {
                /*
                 * By default, this is a real-time short-text speech synthesis request. It supports synthesizing up to 300 characters at a time.
                 * A Chinese character, an English letter, or a punctuation mark is counted as one character.
                 * Text exceeding 300 characters will cause an error or be truncated.
                 * For text longer than 300 characters, consider using long-text speech synthesis.
                 */
                syPtr = nlsClient.CreateSynthesizerRequest(TtsVersion.ShortTts);
                if (syPtr.native_request != IntPtr.Zero)
                {
                    nlsResult.Text = "CreateSynthesizerRequest Success";
                }
                else
                {
                    nlsResult.Text = "CreateSynthesizerRequest Failed";
                }
                cur_sy_closed = "null";
                cur_sy_completed = "null";
            }
    
            // start synthesizer
            private void button10_Click(object sender, EventArgs e)
            {
                int ret = -1;
                if (syPtr.native_request != IntPtr.Zero)
                {
                    syPtr.SetAppKey(syPtr, appKey);
                    syPtr.SetToken(syPtr, token);
                    syPtr.SetUrl(syPtr, url);
                    syPtr.SetText(syPtr, "The weather is great today, I want to go play soccer on the field.");
                    syPtr.SetVoice(syPtr, "siqi");
                    syPtr.SetVolume(syPtr, 50);
                    syPtr.SetFormat(syPtr, "wav");
                    syPtr.SetSampleRate(syPtr, 16000);
                    syPtr.SetSpeechRate(syPtr, 0);
                    syPtr.SetPitchRate(syPtr, 0);
                    syPtr.SetEnableSubtitle(syPtr, true); // Enable captions
                    
                    string uuid = System.Guid.NewGuid().ToString("N");
    
                    syPtr.SetOnSynthesisCompleted(syPtr, DemoOnSynthesisCompleted, uuid);
                    syPtr.SetOnBinaryDataReceived(syPtr, DemoOnBinaryDataReceived, uuid);
                    syPtr.SetOnTaskFailed(syPtr, DemoOnSynthesisTaskFailed, uuid);
                    syPtr.SetOnChannelClosed(syPtr, DemoOnSynthesisClosed, uuid);
                    syPtr.SetOnMetaInfo(syPtr, DemoOnMetaInfo, uuid);
    
                    ret = syPtr.Start(syPtr);
                }
    
                if (ret != 0)
                {
                    nlsResult.Text = "Synthesizer Start failed";
                }
                else
                {
                    nlsResult.Text = "Synthesizer Start success";
                }
            }
    
            // cancel synthesizer
            private void button9_Click(object sender, EventArgs e)
            {
                int ret = -1;
                if (syPtr.native_request != IntPtr.Zero)
                    ret = syPtr.Cancel(syPtr);
    
                if (ret != 0)
                {
                    nlsResult.Text = "Synthesizer Cancel failed";
                }
                else
                {
                    nlsResult.Text = "Synthesizer Cancel success";
                }
            }
    
            private void btnSYrelease_Click(object sender, EventArgs e)
            {
                if (syPtr.native_request != IntPtr.Zero)
                {
                    nlsClient.ReleaseSynthesizerRequest(syPtr);
                    syPtr.native_request = IntPtr.Zero;
                    nlsResult.Text = "ReleaseSynthesizerRequest Success";
                }
                else
                {
                    nlsResult.Text = "ReleaseSynthesizerRequest is nullptr";
                }
                cur_sy_closed = "null";
                cur_sy_completed = "null";
            }
        }
    }