Go SDK

Updated at:

Use the Go SDK for short-sentence speech recognition to send audio and receive recognition results through callbacks. This topic provides installation instructions, a complete example, and descriptions of connection settings, recognition methods, and logging.

Prerequisites

Install the SDK

Run the following command in your Go module directory:

go get github.com/aliyun/alibabacloud-nls-go-sdk

If the project does not have a module yet, run go mod init <module-path> first. The SDK import path is github.com/aliyun/alibabacloud-nls-go-sdk, and its package name is nls.

Code example

The example uses Go SDK v1.1.1 to recognize one audio file. Prepare the following before running it:

  • Set NLS_APP_KEY and NLS_TOKEN in the program's runtime environment. The example reads these variables through os.Getenv for the project Appkey and access token, respectively.

  • Download the sample audio file test1.pcm to the program's working directory. This is a 16 kHz, mono, 16-bit PCM file. To use another file, change audioPath and ensure that its format and sample rate match the recognition parameters and the project model.

package main

import (
    "fmt"
    "io"
    "log"
    "os"
    "time"

    nls "github.com/aliyun/alibabacloud-nls-go-sdk"
)

func waitResult(ch <-chan bool) error {
    select {
    case success, ok := <-ch:
        if !ok || !success {
            return fmt.Errorf("recognition task failed")
        }
        return nil
    case <-time.After(20 * time.Second):
        return fmt.Errorf("timed out waiting for recognition event")
    }
}

func printEvent(text string, param interface{}) {
    fmt.Println(text)
}

func recognize() error {
    appkey := os.Getenv("NLS_APP_KEY")
    token := os.Getenv("NLS_TOKEN")
    if appkey == "" || token == "" {
        return fmt.Errorf("set NLS_APP_KEY and NLS_TOKEN")
    }
    audioPath := "test1.pcm"
    audio, err := os.Open(audioPath)
    if err != nil {
        return err
    }
    defer audio.Close()

    config := nls.NewConnectionConfigWithToken(nls.DEFAULT_URL, appkey, token)
    logger := nls.NewNlsLogger(os.Stderr, "NLS ", log.LstdFlags)
    sr, err := nls.NewSpeechRecognition(
        config, logger, printEvent, nil, nil, printEvent, nil, nil,
    )
    if err != nil {
        return err
    }
    defer sr.Shutdown()

    params := nls.DefaultSpeechRecognitionParam()
    started, err := sr.Start(params, nil)
    if err != nil {
        return err
    }
    if err := waitResult(started); err != nil {
        return err
    }

    // Send 320 bytes every 10 ms for 16 kHz, 16-bit, mono PCM.
    buffer := make([]byte, 320)
    for {
        n, readErr := io.ReadFull(audio, buffer)
        if readErr != nil && readErr != io.EOF && readErr != io.ErrUnexpectedEOF {
            return readErr
        }
        if n > 0 {
            if err := sr.SendAudioData(buffer[:n]); err != nil {
                return err
            }
            time.Sleep(10 * time.Millisecond)
        }
        if readErr == io.EOF || readErr == io.ErrUnexpectedEOF {
            break
        }
    }

    completed, err := sr.Stop()
    if err != nil {
        return err
    }
    return waitResult(completed)
}

func main() {
    if err := recognize(); err != nil {
        log.Fatal(err)
    }
}

Recognition results are returned in payload.result of the RecognitionCompleted callback message. If the task fails, the TaskFailed callback message provides error details.

Connection settings

ConnectionConfig stores connection settings. We recommend caching tokens obtained with an AccessKey pair and refreshing them based on the returned expiration time. Frequent token requests can cause throttling.

Configuration fields

Field

Type

Description

Url

string

The WebSocket endpoint of the speech service. You can use nls.DEFAULT_URL.

Appkey

string

The project Appkey.

Token

string

The access token. Required when initializing with a token.

Akid

string

The AccessKey ID. Required together with Akkey when initializing from JSON without a token.

Akkey

string

The AccessKey secret. Required together with Akid when initializing from JSON without a token.

The constructors populate the settings required for a connection. If you construct a ConnectionConfig struct directly, obtain and set Token in advance. Setting Akid and Akkey in the struct does not retrieve a token automatically.

Initialization methods

Use a token

Create a configuration with the service endpoint, project Appkey, and token.

func NewConnectionConfigWithToken(url string, appkey string, token string) *ConnectionConfig

Returns a pointer to the connection configuration: *ConnectionConfig.

Use an AccessKey pair

Obtain a token with an AccessKey pair and create a configuration. This method uses the authentication settings specified by DEFAULT_DISTRIBUTE, DEFAULT_DOMAIN, and DEFAULT_VERSION.

func NewConnectionConfigWithAKInfoDefault(url string, appkey string, akid string, akkey string) (*ConnectionConfig, error)

Returns a pointer to the connection configuration and an error. Handle a non-nil error before using the configuration.

Use JSON

Create a configuration from a JSON string.

func NewConnectionConfigFromJson(jsonStr string) (*ConnectionConfig, error)

The valid fields in jsonStr are url, appkey, token, akid, and akkey. Both url and appkey are required. If token is nonempty, it is used directly. Otherwise, provide both akid and akkey so that the default AccessKey initialization method can obtain a token.

Returns a pointer to the connection configuration and an error. An error is returned for invalid JSON, missing required fields, or failure to obtain a token.

Recognition parameters and methods

Recognition parameters

SpeechRecognitionStartParam specifies recognition parameters.

Field

Type

Description

Format

string

The audio format. You can use the PCM, WAV, OPUS, and OPU constants. Encode the audio yourself when using OPUS or OPU. The data sent must match the specified format.

SampleRate

int

The audio sample rate in Hz. It must match the audio and the project model.

EnableIntermediateResult

bool

Specifies whether to return intermediate results. true: enabled. false: disabled.

EnablePunctuationPrediction

bool

Specifies whether to enable punctuation prediction. true: enabled. false: disabled.

EnableInverseTextNormalization

bool

Specifies whether to enable inverse text normalization (ITN), which can convert Chinese numbers to Arabic numerals. true: enabled. false: disabled.

DefaultSpeechRecognitionParam() takes no arguments and returns a SpeechRecognitionStartParam: Format is pcm, SampleRate is 16000, and all three Boolean fields are true. Modify the returned struct as needed before passing it to Start.

func DefaultSpeechRecognitionParam() SpeechRecognitionStartParam

When you construct the parameter struct directly, Boolean fields that are not assigned have the zero value false.

Create a recognition instance

NewSpeechRecognition creates a short-sentence speech recognition instance and returns *SpeechRecognition and error.

func NewSpeechRecognition(
    config *ConnectionConfig,
    logger *NlsLogger,
    taskfailed func(string, interface{}),
    started func(string, interface{}),
    resultchanged func(string, interface{}),
    completed func(string, interface{}),
    closed func(interface{}),
    param interface{},
) (*SpeechRecognition, error)

Parameter

Type

Description

config

*ConnectionConfig

The connection configuration. See Connection settings.

logger

*NlsLogger

The logger. If nil, the default logger is used. See SDK logging.

taskfailed

func(string, interface{})

The callback for TaskFailed events. Receives task failure messages.

started

func(string, interface{})

The callback for RecognitionStarted events, which indicate that the recognition task has started.

resultchanged

func(string, interface{})

The callback for RecognitionResultChanged events. Receives intermediate results.

completed

func(string, interface{})

The callback for RecognitionCompleted events. Receives final results.

closed

func(interface{})

The callback for a server notification that the connection is closed. When calling Shutdown yourself, release resources in the calling code rather than relying on this callback.

param

interface{}

A custom value passed to each callback as a single argument. Message callbacks receive the message string as their first argument and this custom value as their second argument.

Start recognition

Start initiates a recognition task.

func (sr *SpeechRecognition) Start(param SpeechRecognitionStartParam, extra map[string]interface{}) (chan bool, error)
  • param: Recognition parameters.

  • extra: Additional request parameters in key:value form. If a field has the same name as a field in param, the value in extra takes precedence. Pass nil if no additional parameters are needed.

  • Return values: error indicates an error while initiating the request. If error is nil, wait for the Boolean value on the returned channel. true indicates that the task has started and audio can be sent. false indicates task failure. Set a timeout when waiting.

Send audio

func (sr *SpeechRecognition) SendAudioData(data []byte) error

data contains audio bytes in the format specified in the recognition parameters. The method returns error. Handle a non-nil error as a send failure.

Stop recognition

After sending the audio, call Stop and wait for the final result.

func (sr *SpeechRecognition) Stop() (chan bool, error)

This method takes no arguments. The returned error indicates an error while stopping the task. If error is nil, wait for the Boolean value on the returned channel. true indicates that a recognition completion event has been received. false indicates task failure. The completed callback receives the final result. Set a timeout when waiting on the channel.

Close the connection

func (sr *SpeechRecognition) Shutdown()

Forcibly closes the connection. Takes no arguments and returns no value. Call this method after recognition completes or an error occurs to release the connection.

SDK constants

Constant

Description

SDK_VERSION

The SDK version identifier included in the request context.

PCM

The PCM audio format. Value: pcm.

WAV

The WAV audio format. Value: wav.

OPUS

The OPUS audio format. Value: opus.

OPU

The OPU audio format. Value: opu.

DEFAULT_DISTRIBUTE

The default region for obtaining tokens. Value: cn-shanghai.

DEFAULT_DOMAIN

The default domain for obtaining tokens. Value: nls-meta.cn-shanghai.aliyuncs.com.

DEFAULT_VERSION

The API version for obtaining tokens. Value: 2019-02-28.

DEFAULT_URL

The default WebSocket endpoint. Value: wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1.

SDK logging

Create a logger

DefaultNlsLog() takes no arguments and returns the global default *NlsLogger. The default logger writes to standard error with the prefix NLS. To create a separate logger, use:

func NewNlsLogger(w io.Writer, tag string, flag int) *NlsLogger

Parameter

Type

Description

w

io.Writer

The log output destination. Any object that implements io.Writer is supported.

tag

string

The log prefix.

flag

int

Log flags, such as date and time flags. See Go log constants.

Configure logging

None of the following methods return a value.

Method

Description

SetLogSil(sil bool)

true: suppresses output from Print, Printf, and Println. false: allows output from these methods. Does not affect the Debug, Fatal, or Panic methods.

SetDebug(debug bool)

true: allows output from Debugf and Debugln. false: disables debug output.

SetOutput(w io.Writer)

Sets the log output destination.

SetPrefix(prefix string)

Sets the log prefix.

SetFlags(flags int)

Sets the log flags. See Go log constants.

Write logs

Method

Description

Print(v ...interface{})

Writes an ordinary log message.

Println(v ...interface{})

Writes an ordinary log message followed by a newline.

Printf(format string, v ...interface{})

Writes an ordinary log message using a format string.

Debugln(v ...interface{})

Writes a debug message followed by a newline.

Debugf(format string, v ...interface{})

Writes a debug message using a format string.

Fatal(v ...interface{})

Writes a log message and calls os.Exit(1) to exit the process.

Fatalln(v ...interface{})

Writes a log message followed by a newline, then calls os.Exit(1) to exit the process.

Fatalf(format string, v ...interface{})

Writes a formatted log message, then calls os.Exit(1) to exit the process.

Panic(v ...interface{})

Writes a log message and triggers panic.

Panicf(format string, v ...interface{})

Writes a formatted log message and triggers panic.

For formatting rules, see the Go log documentation.