C++ demo

Updated at:

This topic describes how to use the C++ software development kit (SDK) for Alibaba Cloud Intelligent Speech Interaction. It provides installation instructions and code examples.

Prerequisites

  • The latest version is 1.2.2, which was released on November 14, 2018.

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

  • You have activated Intelligent Speech Interaction and obtained an AccessKey ID and AccessKey secret. For more information, see Getting started.

Example description

The audio file recognition example uses the AlibabaNlsCommon::FileTrans object of the nlsCommonSDK to submit recognition requests and query results. The example uses Remote Procedure Call (RPC)-style POP API calls.

Download and installation

Download the nlsCommonSDK. The downloaded file contains the following items:

  • CMakeLists.txt: The CMakeLists file for the sample code-based project.

  • readme.txt: The SDK instructions.

  • release.log: The update history.

  • version: The version number.

  • build.sh: The compilation script for the demo.

  • demo: The sample file.

    File name

    Description

    fileTransDemo.cpp

    An audio file recognition example.

  • include the following: Contains the SDK header files and some third-party header files. The files are described in the following table.

    File name

    Description

    openssl

    The OpenSSL header file folder for Linux.

    curl

    The curl header file folder.

    uuid

    The UUID header file folder for Linux.

    json

    The jsoncpp header file folder.

    Global.h

    The global declaration header file.

    FileTrans.h

    The audio file recognition header file.

  • lib: Contains the curl and jsoncpp dynamic libraries.

    The software versions required to load the library files vary based on your platform:

    • Linux (Glibc 2.5 or later, Gcc4 or Gcc5)

    • Windows (VS2013, VS2015)

    To compile and run the program:

    Important

    • The following tools are required to install the SDK on Linux:

      • Glibc 2.5 or later

      • Gcc4 or Gcc5

    • On Windows, you must build the sample project. Change the encoding format of the sample file to UTF-8 with a bill of materials (BOM). The following libraries are dependencies:

      • openssl-1.0.2j

      • libuuid-1.0.3

      • curl-7.60.0

      • jsoncpp-0.10.6

    Assume that the sample file is decompressed to the path/to directory. To compile and run the program, run the following commands in sequence in the Linux terminal.

  • CMake support:

    Make sure that CMake 2.4 or later is installed on your local system.

    1. Switch to the directory: cd path/to/sdk/lib.

    2. Decompress the file: tar -zxvpf linux.tar.gz.

    3. Switch to the directory: cd path/to/sdk.

    4. Run the compilation script: ./build.sh.

    5. Switch to the directory: cd path/to/sdk/demo.

    6. You can run the file recognition sample program: ./fileTransDemo your-AccessKeyId your-AccessKeySecret your-appkey.

  • CMake is not supported.

    1. Switch to the directory: cd path/to/sdk/lib.

    2. Decompress the file: tar -zxvpf linux.tar.gz.

    3. Switch to the directory: cd path/to/sdk/demo.

    4. Use the g++ command to compile the sample program: g++ -o fileTransDemo fileTransDemo.cpp -I path/to/sdk/include/ -L path/to/sdk/lib/linux -ljsoncpp -lssl -lcrypto -lcurl -luuid -lalibabacloud-idst-common -D_GLIBCXX_USE_CXX11_ABI=0.

    5. Specify the library path: export LD_LIBRARY_PATH=path/to/sdk/lib/linux/.

    6. Run the file recognition sample program: ./fileTransDemo your-AccessKeyId your-AccessKeySecret your-appkey.

Key interface

FileTrans: The audio file recognition object. You can use this object to obtain recognition results, failure information, and other data.

Code example

Note

Download nls-sample-16k.wav. The sample audio file uses the PCM encoding format with a 16000 Hz sample rate. In the console, the model is set to the general-purpose model. If you use a different audio file, you must enter the corresponding encoding format and sample rate, and set the corresponding model in the console. For more information about model settings, see Manage projects.

#include <iostream>
#include <string>
#include "FileTrans.h"

#ifdef _WIN32
#include <windows.h>
#endif // _WIN32

using std::string;
using std::cout;
using std::endl;
using namespace AlibabaNlsCommon;

#if defined _WIN32
string UTF8ToGBK(const string &strUTF8) {

        int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
        unsigned short * wszGBK = new unsigned short[len + 1];
        memset(wszGBK, 0, len * 2 + 2);

        MultiByteToWideChar(CP_UTF8, 0, (char*)strUTF8.c_str(), -1, (wchar_t*)wszGBK, len);

        len = WideCharToMultiByte(CP_ACP, 0, (wchar_t*)wszGBK, -1, NULL, 0, NULL, NULL);

        char *szGBK = new char[len + 1];
        memset(szGBK, 0, len + 1);
        WideCharToMultiByte(CP_ACP, 0, (wchar_t*)wszGBK, -1, szGBK, len, NULL, NULL);

        string strTemp(szGBK);
        delete[] szGBK;
        delete[] wszGBK;

        return strTemp;
}
#endif

// Audio file recognition
int fileTrans(const char* accessKeyId, const char* accessKeySecret, const char* appKey, const char* fileLink) {
    FileTrans request;

    /* Set the AccessKey ID of your Alibaba Cloud account. */
    request.setAccessKeyId(accessKeyId);
    /* Set the AccessKey secret of your Alibaba Cloud account. */
    request.setKeySecret(accessKeySecret);
    /* Set the AppKey of your Alibaba Cloud account. */
    request.setAppKey(appKey);
    /* Set the URL of the audio file. */
    request.setFileLinkUrl(fileLink);
    /* Set the domain name for the Lite version. The default is the China (Shanghai) region. To use other regions, see the POP call parameters for each region. */
    request.setDomain("speechfiletranscriberlite.cn-shanghai.aliyuncs.com");
    /* Set the version for the Lite version connection. */
    request.setServerVersion("2021-12-21");
    /* Set the connection region. */
    request.setRegionId("cn-shanghai");

    /* Start audio file recognition. 0 is returned on success, and -1 on failure. */
    int ret = request.applyFileTrans();
    if (-1 == ret) {
        cout << "FileTrans failed: " << request.getErrorMsg() << endl; /* Get the cause of the failure. */
        return -1;
    } else {
        string result = request.getResult();

#ifdef _WIN32
        result = UTF8ToGBK(result);
#endif

                cout << "FileTrans succeeded: " << result << endl;

                return 0;
    }
}

int main(int argc, char* argv[]) {
    if (argc < 4) {
        cout << "FileTransDemo needs params: <AccessKey Id> <AccessKey Secret> <app-key>" << endl;
        return -1;
    }

    const char* accessKeyId = argv[1];
    const char* accessKeySecret = argv[2];
    const char* appKey = argv[3];
    const char* fileLink = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav";

    fileTrans(accessKeyId, accessKeySecret, appKey, fileLink);

    return 0;
}

FAQ

Can I use a GCC version later than 5.0 to compile the C++ SDK (version 3.0 or later) for speech synthesis and speech recognition?

Yes, you can. On Linux, GCC 4.8.5 or later is supported. The SDK has been verified to compile and run successfully with GCC versions 4.8.5, 5.5.0, and 8.4.0.

Why can't I connect to the framework?

This may be because the code in the framework is a mix of Objective-C and C++. Therefore, you must use a file with the .mm extension to make calls. You must also make sure that the header file path and library file path are set correctly in your project.

What does the SDK error "DNS resolved timeout" mean?

Check the `nameserver` settings in the /etc/resolv.conf file. We recommend that you add the following nameserver as the first entry: nameserver 114.114.114.114.

How do I resolve the "DNS: resolved timeout" error for a C++ SDK ASR request?

  • Earlier versions (3.0 and earlier): This issue can occur during periods of high concurrency or when the computer's DNS is busy. To resolve this issue, upgrade to version 3.1.X or restart the request.

  • Later versions (3.0 and later): This issue has been addressed in later versions. If it still occurs, it is likely because the computer's DNS is busy. In this case, you must restart the request.

When I integrate the new C++ SDK into another project and change add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0) to add_definitions(-D_GLIBCXX_USE_CXX11_ABI=1) in CMakeLists.txt, the compilation fails. How do I fix this?

You must modify this parameter for the entire project, not just in the CMakeLists.txt file. For example, you must also modify the parameter in config/linux.thirdparty.debug.cmake and config/linux.thirdparty.release.cmake. Search the entire directory for _GLIBCXX_USE_CXX11_ABI and modify all instances of the parameter.

When I use the C++ SDK on Windows, it reports a missing nlsCommonSdk.dll file. How do I fix this?

The nlsCommonSdk.dll file is not included in version 3.1 and later.

What is the difference between the old C++ SDK (NlsSdkCpp2.0) and the new one (NlsSdkCpp3.X)?

In NlsSdkCpp2.0, each request runs in a separate thread, and the interfaces are synchronous.

In NlsSdkCpp3.X, the third-party library libevent handles event messages internally. This design provides better concurrent performance, and the interfaces are asynchronous.

Does the C++ SDK not support the C11 standard? My project cannot link to the SDK. How do I fix this?

The project defaults to _GLIBCXX_USE_CXX11_ABI=0. To resolve the linking issue, you must modify this parameter for the entire project. Search the project directory for _GLIBCXX_USE_CXX11_ABI and modify all instances.

The C++ SDK demo runs successfully, but my integrated project fails with a DNS resolution error: "nls-gateway-cn-shanghai.aliyuncs.com dns failed: nodename nor servname provided, or not known". How do I fix this?

  1. The SDK attempts DNS resolution using all protocol families, such as IPv4 and IPv6, that are enabled on the current device. The domain name nls-gateway-cn-shanghai.aliyuncs.com does not support IPv6. This causes a resolution error and forces the SDK to exit. To resolve this issue, you can disable the IPv6 protocol on the current device. This setting will be configurable in future versions of the C++ SDK.

  2. Upgrade to version 3.1.12 or later.

The C++ SDK demo runs successfully, but my integrated project fails with a network connection error: "[dnsEventCallback:465]... Connect failed:Network is unreachable. retry...". How do I fix this?

This error indicates a network connection failure. The logs show that a connection cannot be established to the IP address that is resolved from the DNS domain name. You can run a ping test to confirm that the network is unreachable. This error occurs because local DNS interception causes the evdns_getaddrinfo function within the SDK's libevent to obtain an incorrect IP address.

Solutions:

  • For versions earlier than 3.1.12, you can manually replace evdns_getaddrinfo() with the system's getaddrinfo().

  • For version 3.1.12, you can modify add_definitions(-DNLS_USE_NATIVE_GETADDRINFO) in the CMakeLists.txt file.

  • Versions 3.1.12 and later include the setDirectHost() interface. You can perform DNS resolution outside the SDK and then use this interface to set the correct IP address.

  • This issue is resolved in version 3.1.13 and later. If the problem persists at runtime, you can call the setUseSysGetAddrInfo(true) interface.

What error message is returned if the text passed for speech synthesis with the C++ SDK is not UTF-8 encoded?

If the input text is not UTF-8 encoded and contains Chinese characters, the call to the start function of the speech synthesis SDK fails. The function returns the error message Socket recv failed, errorCode: 0. An error code of 0 indicates that the server closed the connection. In this case, you must check whether the input text is UTF-8 encoded.