Go demo

更新时间:
复制 MD 格式

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

Prerequisites

  • Before you use the SDK, review the API reference. For more information, see the 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

  • This example demonstrates how to use the CommonRequest method of the Go SDK to submit a transcription request and query the result. The example uses the RPC-style POP API call method.

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

  • For more information about how to use the CommonRequest method of the Go SDK, see Make calls using CommonRequest.

Install the SDK

The Alibaba Cloud Go SDK supports Go 1.7 and later. You can install the SDK 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

Procedure

  1. Create and initialize an Alibaba Cloud credential object. Use the AccessKey ID and AccessKey secret from your Alibaba Cloud account for authentication.

  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 obtain the task ID.

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

  5. Use polling to query the transcription result.

Code example

  • Download nls-sample-16k.wav. This audio file is in the PCM encoding format with a sample rate of 16000 Hz. This example uses the general-purpose model, which is specified in the console. If you use a different audio file, you must specify its encoding format and sample rate, and select the corresponding model in the console. For more information about how to configure a model, see Manage projects.

  • Before you call the API, configure environment variables to provide 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.

package main
import (
    "encoding/json"
    "fmt"
    "os"
    "time"
    "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"
)
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 = "SpeechFileTranscriberLite"
    const DOMAIN string = "speechfiletranscriberlite.cn-shanghai.aliyuncs.com"
    const API_VERSION string = "2021-12-21"
    const POST_REQUEST_ACTION string = "SubmitTask"
    const GET_REQUEST_ACTION  string = "GetTaskResult"
    // Request parameters
    const KEY_APP_KEY string = "appkey"
    const KEY_FILE_LINK string = "file_link"
    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
    // Specifies whether to output word-level timestamps. Default value: false.
    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 audio file transcription 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 audio file transcription request was successful.")
        taskId = postMapResult[KEY_TASK_ID].(string)
    } else {
        fmt.Println("The audio file transcription 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: ", getResponseContent)
        if (getResponse.GetHttpStatus() != 200) {
            fmt.Println("The request to query the transcription result 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 audio file was successfully transcribed.")
    } else {
        fmt.Println("The audio file transcription failed.")
    }
}