Go Demo

更新时间:
复制 MD 格式

This topic describes how to use the Go software development kit (SDK) for Intelligent Speech Interaction and provides 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 an AccessKey secret. For more information, see Get started.

Example description

  • The recording file recognition example uses the `CommonRequest` method of the Go SDK to submit recognition requests and query for results. This example uses the remote procedure call (RPC) style for POP API calls.

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

  • For more information about how to use `CommonRequest` in the Go SDK, see Use CommonRequest to make calls.

SDK installation

The Alibaba Cloud Go SDK supports Go 1.7 and later. You can install it in one of the following ways:

  • Use Glide (recommended):

    glide get github.com/aliyun/alibaba-cloud-sdk-go
  • Use govendor:

    go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk

Call procedure

  1. Create and initialize an Alibaba Cloud authentication object.

    Use your Alibaba Cloud account's AccessKey ID and AccessKey secret for authentication.

  2. Create a recording file recognition request and set the request parameters.

  3. Submit the recording file recognition request and process the server-side response to obtain the task ID.

  4. Create a recognition result query request. Set the query parameter to the task ID.

  5. Poll for the recognition result.

Code example

  • Download nls-sample-16k.wav. This recording is in the PCM encoding format and has a sample rate of 16000 Hz. The model for this example is the general-purpose model, which is set in the console. If you use a different recording, 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.

  • Before you call the API, configure environment variables to load your access credentials. The environment variables for the AccessKey ID, AccessKey secret, and the AppKey for Intelligent Speech Interaction are ALIYUN_AK_ID, ALIYUN_AK_SECRET, and NLS_APP_KEY respectively.

package main
import (
    "encoding/json"
    "fmt"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/credentials"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
    "os"
    "time"
)
func main() {
    // The region ID. This is a static field.
    const REGION_ID string = "cn-shanghai"
    const ENDPOINT_NAME string = "cn-shanghai"
    const PRODUCT string = "nls-filetrans"
    const DOMAIN string = "filetrans.cn-shanghai.aliyuncs.com"
    const API_VERSION string = "2018-08-17"
    const POST_REQUEST_ACTION string = "SubmitTask"
    const GET_REQUEST_ACTION  string = "GetTaskResult"
    // Request parameters.
    const KEY_APP_KEY string = "appkey"      // You do not need to replace the appkey here.
    const KEY_FILE_LINK string = "file_link"
    const KEY_VERSION string = "version"
    const KEY_ENABLE_WORDS string = "enable_words"
    // Response parameters.
    const KEY_TASK string = "Task"
    const KEY_TASK_ID string = "TaskId"
    const KEY_STATUS_TEXT string = "StatusText"
    const KEY_RESULT string = "Result"
    // Status values.
    const STATUS_SUCCESS string = "SUCCESS"
    const STATUS_RUNNING string = "RUNNING"
    const STATUS_QUEUEING string = "QUEUEING"
    // To obtain an AccessKey ID and AccessKey secret, go to the console: https://ram.console.aliyun.com/manage/ak
    var accessKeyId string = os.Getenv("ALIYUN_AK_ID")
    var accessKeySecret string = os.Getenv("ALIYUN_AK_SECRET")
    var appKey string = os.Getenv("NLS_APP_KEY")
    var fileLink string = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav"
    c := sdk.NewConfig()
    credential := credentials.NewAccessKeyCredential(accessKeyId, accessKeySecret)
    client, err := sdk.NewClientWithOptions(REGION_ID, c, credential)
    if err != nil {
        panic(err)
    }
    postRequest := requests.NewCommonRequest()
    postRequest.Domain = DOMAIN
    postRequest.Version = API_VERSION
    postRequest.Product = PRODUCT
    postRequest.ApiName = POST_REQUEST_ACTION
    postRequest.Method = "POST"
    mapTask := make(map[string]string)
    mapTask[KEY_APP_KEY] = appKey
    mapTask[KEY_FILE_LINK] = fileLink
    // If you are a new user, use version 4.0. If you are an existing user and want to continue using the default version 2.0, comment out this parameter setting.
    mapTask[KEY_VERSION] = "4.0"
    // Specifies whether to output word-level information. The default value is false. To enable this feature, you must set version to 4.0.
    mapTask[KEY_ENABLE_WORDS] = "false"
    task, err := json.Marshal(mapTask)
    if err != nil {
        panic(err)
    }
    postRequest.FormParams[KEY_TASK] = string(task)
    postResponse, err := client.ProcessCommonRequest(postRequest)
    if err != nil {
        panic(err)
    }
    postResponseContent := postResponse.GetHttpContentString()
    fmt.Println(postResponseContent)
    if (postResponse.GetHttpStatus() != 200) {
        fmt.Println("The recording file recognition request failed. HTTP error code: ", postResponse.GetHttpStatus())
        return
    }
    var postMapResult map[string]interface{}
    err = json.Unmarshal([]byte(postResponseContent), &postMapResult)
    if err != nil {
        panic(err)
    }
    var taskId string = ""
    var statusText string = ""
    statusText = postMapResult[KEY_STATUS_TEXT].(string)
    if statusText == STATUS_SUCCESS {
        fmt.Println("The recording file recognition request was successful.")
        taskId = postMapResult[KEY_TASK_ID].(string)
    } else {
        fmt.Println("The recording file recognition request failed.")
        return
    }
    getRequest := requests.NewCommonRequest()
    getRequest.Domain = DOMAIN
    getRequest.Version = API_VERSION
    getRequest.Product = PRODUCT
    getRequest.ApiName = GET_REQUEST_ACTION
    getRequest.Method = "GET"
    getRequest.QueryParams[KEY_TASK_ID] = taskId
    statusText = ""
    for true {
        getResponse, err := client.ProcessCommonRequest(getRequest)
        if err != nil {
            panic(err)
        }
        getResponseContent := getResponse.GetHttpContentString()
        fmt.Println("Query result for the recognition task: ", getResponseContent)
        if (getResponse.GetHttpStatus() != 200) {
            fmt.Println("The recognition result query request failed. HTTP error code: ", getResponse.GetHttpStatus())
            break
        }
        var getMapResult map[string]interface{}
        err = json.Unmarshal([]byte(getResponseContent), &getMapResult)
        if err != nil {
            panic(err)
        }
        statusText = getMapResult[KEY_STATUS_TEXT].(string)
        if statusText == STATUS_RUNNING || statusText == STATUS_QUEUEING {
            time.Sleep(10 * time.Second)
        } else {
            break
        }
    }
    if statusText == STATUS_SUCCESS {
        fmt.Println("The recording file was recognized successfully.")
    } else {
        fmt.Println("The recording file recognition failed.")
    }
}