.NET demo

Updated at:

This topic describes how to use the .NET SDK for Alibaba Cloud Intelligent Speech Interaction. It includes installation instructions and code examples.

Prerequisites

  • 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 Get started.

About the example

  • This example shows how to use the CommonRequest class of the .NET SDK to submit transcription requests and query the results. The example uses the RPC-style POP API.

  • For more information about the Alibaba Cloud .NET SDK, see Use the .NET SDK.

  • For more information about how to use CommonRequest in the .NET SDK, see Make calls using CommonRequest.

Install the SDK

You only need to install the core library of the Alibaba Cloud .NET SDK. You can use one of the following two methods:

  • Add a DLL reference to the core library

    1. Go to the .NET SDK release list. In the SDK Core Library section, click DLL Reference for .NET 4.0 and later on the right.

    2. In Solution Explorer in Visual Studio, right-click your project, and then click Reference.

    3. In the menu that appears, click Add Reference.

    4. In the dialog box that appears, click Browse, select the downloaded DLL file, and then click OK.

  • Importing a project

    1. Run the following command on the command line to download the SDK source code from GitHub.

      git clone https://github.com/aliyun/aliyun-openapi-net-sdk.git

      The aliyun-net-sdk-core/aliyun-net-sdk-core.vs2017.csproj file in the aliyun-openapi-net-sdk directory is the .NET project file for Visual Studio 2017.

    2. In the Visual Studio interface, right-click your solution.

    3. Select Add > Existing Project.

    4. In the dialog box that appears, select the corresponding .NET project file from the source code, such as aliyun-net-sdk-core.vs2010.csproj, and click Open.

    5. Right-click your project, and select Reference > Add Reference.

Procedure

  1. Create and initialize an AcsClient.

  2. Create an audio file transcription request and set the request parameters.

  3. Submit the audio file transcription request, process the server-side response, and retrieve the task ID.

  4. Create a request to query the transcription result and set the task ID as a query parameter.

  5. Poll for the transcription result.

Code example

Note

Download nls-sample-16k.wav. This audio file is in the PCM format with a 16000 Hz sample rate. The model used in this example is the general-purpose model, which is set in the console. If you use other audio files, specify the corresponding encoding format and sample rate in the request parameters, and set the corresponding model in the console. For more information about how to set the model, see Manage projects.

using System;
using Newtonsoft.Json.Linq;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Http;
namespace FileTrans
{
    class FileTrans
    {
        // The region ID. This is a static field.
        public const string REGIONID = "cn-shanghai";
        public const string PRODUCT = "SpeechFileTranscriberLite";
        public const string DOMAIN = "speechfiletranscriberlite.cn-shanghai.aliyuncs.com";
        public const string API_VERSION = "2021-12-21";
        public const string POST_REQUEST_ACTION = "SubmitTask";
        public const string GET_REQUEST_ACTION = "GetTaskResult";
        // Request parameters
        public const string KEY_APP_KEY = "appkey";
        public const string KEY_FILE_LINK = "file_link";
        public const string KEY_ENABLE_WORDS = "enable_words";
        // Response parameters
        public const string KEY_TASK = "Task";
        public const string KEY_TASK_ID = "TaskId";
        public const string KEY_STATUS_TEXT = "StatusText";
        // Status values
        public const string STATUS_SUCCESS = "SUCCESS";
        public const string STATUS_RUNNING = "RUNNING";
        public const string STATUS_QUEUEING = "QUEUEING";
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                System.Console.WriteLine("FileTrans Demo need params: <AccessKey Id> <AccessKey Secret> <app-key>");
                return;
            }
            string accessKeyId = args[0];
            string accessKeySecret = args[1];
            string appKey = args[2];
            string fileLink = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav";
            /**
             * Create an Alibaba Cloud authentication object.
             */
            IClientProfile profile = DefaultProfile.GetProfile(
                REGIONID,
                accessKeyId,
                accessKeySecret
                );
            DefaultAcsClient client = new DefaultAcsClient(profile);
            try
            {
                /**
                 * Create an audio file transcription request and set the request parameters.
                 */
                CommonRequest request = new CommonRequest();
                request.Domain = DOMAIN;
                request.Version = API_VERSION;
                request.Action = POST_REQUEST_ACTION;
                request.Product = PRODUCT;
                request.Method = MethodType.POST;
                // Set the task. Set it to the request body as a JSON string.
                JObject obj = new JObject();
                obj[KEY_APP_KEY] = appKey;
                obj[KEY_FILE_LINK] = fileLink;
                // Specify whether to output word-level information. The default value is false.
                obj[KEY_ENABLE_WORDS] = false;
                string task = obj.ToString();
                request.AddBodyParameters(KEY_TASK, task);
                /**
                 * Submit the audio file transcription request and process the server-side response.
                 */
                CommonResponse response = client.GetCommonResponse(request);
                System.Console.WriteLine(response.Data);
                if (response.HttpStatus != 200)
                {
                    System.Console.WriteLine("The audio file transcription request failed: " + response.HttpStatus);
                    return;
                }
                // Get the task ID of the audio file transcription request for querying the transcription result.
                string taskId = "";
                JObject jsonObj = JObject.Parse(response.Data);
                string statusText = jsonObj[KEY_STATUS_TEXT].ToString();
                if (statusText.Equals(STATUS_SUCCESS))
                {
                    System.Console.WriteLine("The audio file transcription request was successful!");
                    taskId = jsonObj[KEY_TASK_ID].ToString();
                }
                else
                {
                    System.Console.WriteLine("The audio file transcription request failed!");
                    return;
                }
                /**
                 * Create a request to query the transcription result and set the task ID as a query parameter.
                 */
                CommonRequest getRequest = new CommonRequest();
                getRequest.Domain = DOMAIN;
                getRequest.Version = API_VERSION;
                getRequest.Action = GET_REQUEST_ACTION;
                getRequest.Product = PRODUCT;
                getRequest.Method = MethodType.GET;
                getRequest.AddQueryParameters(KEY_TASK_ID, taskId);
                /**
                 * Submit the request to query the audio file transcription result.
                 * Poll for the transcription result until the server-side returns a status of "SUCCESS" or "SUCCESS_WITH_NO_VALID_FRAGMENT",
                 * or an error. Then, stop polling.
                 */
                statusText = "";
                while (true)
                {
                    CommonResponse getResponse = client.GetCommonResponse(getRequest);
                    System.Console.WriteLine(getResponse.Data);
                    if (getResponse.HttpStatus != 200)
                    {
                        System.Console.WriteLine("The request to query the transcription result failed. HTTP error code: " + getResponse.HttpStatus);
                        break;
                    }
                    JObject jsonObj2 = JObject.Parse(getResponse.Data);
                    statusText = jsonObj2[KEY_STATUS_TEXT].ToString();
                    if (statusText.Equals(STATUS_RUNNING) || statusText.Equals(STATUS_QUEUEING))
                    {
                        // Continue polling.
                        System.Threading.Thread.Sleep(10 * 1000);
                    }
                    else
                    {
                        // Stop polling.
                        break;
                    }
                }
                if (statusText.Equals(STATUS_SUCCESS))
                {
                    System.Console.WriteLine("The audio file was transcribed successfully!");
                }
                else {
                    System.Console.WriteLine("The audio file transcription failed!");
                }
            }
            catch (ServerException ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
            catch (ClientException ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
        }
    }
}