Go SDK

Updated at:

This topic describes how to use the Go SDK for Alibaba Cloud Voice Service. It includes installation instructions and code samples.

Prerequisites

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

Download and install

Note
  • The SDK supports Go 1.16 and later.

  • Make sure that you have installed and configured the Go environment.

  1. Download and install the SDK.

    Run the following command to download and install the SDK.

    go get github.com/aliyun/alibabacloud-nls-go-sdk
  2. Import the SDK.

    Add the following import statement to your code to import the SDK.

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

SDK constants

Constant

Description

SDK_VERSION

The SDK version.

PCM

The PCM audio format.

WAV

The WAV audio format.

OPUS

The OPUS audio format.

OPU

The OPU audio format.

DEFAULT_DISTRIBUTE

The default region used to obtain a token. The default value is "cn-shanghai".

DEFAULT_DOMAIN

The default URL used to obtain a token. The default value is "nls-meta.cn-shanghai.aliyuncs.com".

DEFAULT_VERSION

The protocol version used to obtain a token. The default value is "2019-02-28".

DEFAULT_URL

The default public cloud URL. The default value is "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1".

Establish a connection

Important

If you use an Akid and Akkey to obtain a token, cache the token. Update the token based on the returned time-to-live (TTL) parameter. Do not call the token acquisition operation frequently because frequent calls can trigger throttling.

1. ConnectionConfig

The basic parameters for establishing a connection.

Parameter description:

Parameter

Type

Description

Url

String

The public cloud URL to access. If you are not sure, you can use the DEFAULT_URL constant.

Token

String

The access token. For more information, see Obtain a token.

Akid

String

The AccessKey ID of your Alibaba Cloud account.

  • This parameter is required if you do not specify the Token parameter.

  • This parameter is optional if you specify the Token parameter.

Akkey

String

The AccessKey Secret of your Alibaba Cloud account.

  • This parameter is required if you do not specify the Token parameter.

  • This parameter is optional if you specify the Token parameter.

Appkey

String

The Appkey of the project. To obtain an Appkey, go to the console.

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

Creates connection parameters from a URL, an Appkey, and a token.

  • Parameter description:

Parameter

Type

Description

Url

String

The public cloud URL to access. If you are not sure, you can use the DEFAULT_URL constant.

Appkey

String

The Appkey of the project. To obtain an Appkey, go to the console.

Token

String

Access token. For more information, see Obtain token overview.

  • Return value:

*ConnectionConfig: A pointer to the connection configuration object.

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

Creates connection parameters from a JSON string.

  • Parameter description:

Parameter

Type

Description

jsonStr

String

A JSON string that describes the connection parameters. Valid fields: url, token, akid, akkey, and appkey. The url and appkey fields are required. If you include the token, you do not need to include akid and akkey.

  • Return value:

*ConnectionConfig: A pointer to the connection configuration object.

Real-time speech recognition

1. SpeechTranscriptionStartParam

Parameters for real-time speech recognition.

Parameter

Type

Description

Format

String

The audio format. Default value: PCM. Valid values: OPUS, OPU, and PCM. If you use OPUS or OPU, you must encode the audio yourself.

SampleRate

Integer

The sample rate. Default value: 16000 Hz.

EnableIntermediateResult

Boolean

Specifies whether to return intermediate recognition results.

  • true: The setting is enabled.

  • false: Shuts down.

EnablePunctuationPrediction

Boolean

Specifies whether to enable automatic punctuation.

  • true: It is enabled.

  • false: Shut down.

EnableInverseTextNormalization

Boolean

Specifies whether to enable inverse text normalization (ITN). ITN converts Chinese numerals in the recognition results to Arabic numerals. If you set this to True, Chinese numerals are converted to Arabic numerals. Default value: False.

MaxSentenceSilence

Integer

The threshold for voice activity detection (VAD). A pause in speech that exceeds this threshold is considered the end of a sentence. Valid values: 200 to 2000 milliseconds. Default value: 800 milliseconds.

enable_words

Boolean

Specifies whether to return word-level timestamps. This feature is disabled by default.

  • true: Enables the feature.

  • false: Disables the feature.

2. func DefaultSpeechTranscriptionParam() SpeechTranscriptionStartParam

Creates a set of default parameters.

  • Parameters: None.

  • Return value:

    SpeechTranscriptionStartParam: The default parameters.

3. func NewSpeechTranscription(...) (*SpeechTranscription, error)

Creates a real-time speech recognition object.

  • Parameter description:

Parameter

Type

Description

config

*ConnectionConfig

For more information, see Establish a connection.

logger

*NlsLogger

For more information, see SDK log.

taskfailed

func(string, interface{})

The callback for handling errors during recognition. `interface{}` is a user-defined parameter.

started

func(string, interface{})

The callback for when the connection is established.

sentencebegin

func(string, interface{})

This is the beginning of a sentence.

sentenceend

func(string, interface{})

This is the conclusion.

resultchanged

func(string, interface{})

The callback for intermediate recognition results.

completed

func(string, interface{})

The callback for the final recognition result.

closed

func(interface{})

The callback for when the connection is closed.

param

interface{}

A user-defined parameter.

  • Return value:

    • *SpeechRecognition: A pointer to the speech recognition object.

    • error: An error.

4. func (st *SpeechTranscription) Start(param SpeechTranscriptionStartParam, extra map[string]interface{}) (chan bool, error)

Starts real-time speech recognition.

  • Parameter description:

Parameter

Type

Description

param

SpeechTranscriptionStartParam

The parameters for real-time speech recognition.

extra

map[string]interface{}

Extra key:value parameters.

  • Return value:

    • chan bool: A channel that indicates the start operation is complete.

    • error: An error.

5. func (st *SpeechTranscription) Stop() (chan bool, error)

Stops the real-time speech recognition.

  • Parameters: None.

  • Return value:

    • chan bool: A channel that indicates that the stop operation is complete.

    • error: A fault or an abnormality.

6. func (st *SpeechTranscription) Ctrl(param map[string]interface{}) error

Sends control commands. For more information about the parameters, see the API reference.

  • This operation has no parameters.

    Parameter

    Type

    Description

    param

    map[string]interface{}

    A custom control command. The content of this map is merged into the payload of the request as key:value pairs.

  • Return value:

    error: An error.

7. func (st *SpeechTranscription) Shutdown()

Forcibly stops real-time speech recognition.

  • Parameters: None.

  • Return value: None.

8. func (sr *SpeechTranscription) SendAudioData(data []byte) error

Sends audio data. The audio format must match the format specified in the parameters.

  • Parameter description:

Parameter

Type

Description

data

[]byte

The audio data.

  • Return value:

error: An error.

SDK logs

1. func DefaultNlsLog() *NlsLogger

Creates a globally unique default log object. The default log uses "NLS" as the prefix and outputs to standard error.

  • Parameters: None.

  • Return value:

NlsLogger: A pointer to the log object.

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

Creates a new log object.

  • Parameter description:

Parameter

Type

Description

w

io.Writer

Any object that implements the io.Writer interface.

tag

String

The log prefix. It is printed at the beginning of each log line.

flag

Integer

The log flag. For more information, see the official Go log documentation.

  • Return value:

NlsLogger: A pointer to the log object.

3. func (logger *NlsLogger) SetLogSil(sil bool)

Specifies whether to output logs to the corresponding io.Writer.

  • Parameter description:

Parameter

Type

Description

sil

Boolean

Specifies whether to disable log output.

  • true: Disabled.

  • false: The operation is allowed.

  • Return value: None.

4. func (logger *NlsLogger) SetDebug(debug bool)

Specifies whether to print debug logs. This setting only affects logs that are output using the Debugf or Debugln methods.

  • Parameter description:

Parameter

Type

Description

debug

Boolean

Specifies whether to enable debug log output.

  • true: The operation is allowed.

  • false: Disabled.

  • Return value: None.

5. func (logger *NlsLogger) SetOutput(w io.Writer)

Sets the log output destination.

  • Parameter description:

Parameter

Type

Description

w

io.Writer

Any object that implements the io.Writer interface.

  • Return value: None.

6. func (logger *NlsLogger) SetPrefix(prefix string)

Sets the prefix for each log line.

  • Parameter description:

Parameter

Type

Description

prefix

String

The log line label. It is output at the beginning of the log line.

  • Return value: None.

7. func (logger *NlsLogger) SetFlags(flags int)

Sets the log properties.

  • Parameter description:

Parameter

Type

Description

flags

Integer

The log properties. For more information, see the official Go documentation.

  • Return value: None.

8. Print logs

Log printing methods:

Method name

Description

func (l *NlsLogger) Print(v ...interface{})

Standard log output.

func (l *NlsLogger) Println(v ...interface{})

Standard log output with an automatic new line at the end.

func (l *NlsLogger) Printf(format string, v ...interface{})

Formatted log output. For more information about the format, see the official Go documentation.

func (l *NlsLogger) Debugln(v ...interface{})

Debug log output with an automatic new line at the end.

func (l *NlsLogger) Debugf(format string, v ...interface{})

Formatted debug log output.

func (l *NlsLogger) Fatal(v ...interface{})

Outputs a fatal error log and then exits the process.

func (l *NlsLogger) Fatalln(v ...interface{})

Outputs a fatal error log with a new line at the end, and then exits the process.

func (l *NlsLogger) Fatalf(format string, v ...interface{})

Outputs a formatted fatal error log and then exits the process.

func (l *NlsLogger) Panic(v ...interface{})

Outputs a fatal error log, prints crash information, and then exits the process.

func (l *NlsLogger) Panicln(v ...interface{})

Outputs a fatal error log with a new line at the end, prints crash information, and then exits the process.

func (l *NlsLogger) Panicf(format string, v ...interface{})

Outputs a formatted fatal error log, prints crash information, and then exits the process.

Code sample

package main

import (
        "errors"
        "flag"
        "fmt"
        "log"
        "os"
        "os/signal"
        "sync"
        "time"

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

const (
    AKID  = "Your AKID"
        AKKEY = "Your AKKEY"
        // Online key
        APPKEY = "Your APPKEY"
        TOKEN  = "Your TOKEN"
)

func onTaskFailed(text string, param interface{}) {
        logger, ok := param.(*nls.NlsLogger)
        if !ok {
                log.Default().Fatal("invalid logger")
                return
        }

        logger.Println("TaskFailed:", text)
}

func onStarted(text string, param interface{}) {
        logger, ok := param.(*nls.NlsLogger)
        if !ok {
                log.Default().Fatal("invalid logger")
                return
        }

        logger.Println("onStarted:", text)
}

func onSentenceBegin(text string, param interface{}) {
        logger, ok := param.(*nls.NlsLogger)
        if !ok {
                log.Default().Fatal("invalid logger")
                return
        }

        logger.Println("onSentenceBegin:", text)
}

func onSentenceEnd(text string, param interface{}) {
        logger, ok := param.(*nls.NlsLogger)
        if !ok {
                log.Default().Fatal("invalid logger")
                return
        }

        logger.Println("onSentenceEnd:", text)
}

func onResultChanged(text string, param interface{}) {
        logger, ok := param.(*nls.NlsLogger)
        if !ok {
                log.Default().Fatal("invalid logger")
                return
        }

        logger.Println("onResultChanged:", text)
}

func onCompleted(text string, param interface{}) {
        logger, ok := param.(*nls.NlsLogger)
        if !ok {
                log.Default().Fatal("invalid logger")
                return
        }

        logger.Println("onCompleted:", text)
}

func onClose(param interface{}) {
        logger, ok := param.(*nls.NlsLogger)
        if !ok {
                log.Default().Fatal("invalid logger")
                return
        }

        logger.Println("onClosed:")
}

func waitReady(ch chan bool, logger *nls.NlsLogger) error {
        select {
        case done := <-ch:
                {
                        if !done {
                                logger.Println("Wait failed")
                                return errors.New("wait failed")
                        }
                        logger.Println("Wait done")
                }
        case <-time.After(20 * time.Second):
                {
                        logger.Println("Wait timeout")
                        return errors.New("wait timeout")
                }
        }
        return nil
}

var lk sync.Mutex
var fail = 0
var reqNum = 0

func testMultiInstance(num int) {
        pcm, err := os.Open("tests/test1.pcm")
        if err != nil {
                log.Default().Fatalln(err)
        }

        buffers := nls.LoadPcmInChunk(pcm, 320)
        param := nls.DefaultSpeechTranscriptionParam()
        config, _ := nls.NewConnectionConfigWithAKInfoDefault(nls.DEFAULT_URL, APPKEY, AKID, AKKEY)
        var wg sync.WaitGroup
        for i := 0; i < num; i++ {
                wg.Add(1)
                go func(id int) {
                        defer wg.Done()
                        strId := fmt.Sprintf("ID%d   ", id)
                        logger := nls.NewNlsLogger(os.Stderr, strId, log.LstdFlags|log.Lmicroseconds)
                        logger.SetLogSil(false)
                        logger.SetDebug(true)
                        logger.Printf("Test Normal Case for SpeechRecognition:%s", strId)
                        st, err := nls.NewSpeechTranscription(config, logger,
                                onTaskFailed, onStarted,
                                onSentenceBegin, onSentenceEnd, onResultChanged,
                                onCompleted, onClose, logger)
                        if err != nil {
                                logger.Fatalln(err)
                                return
                        }

                        test_ex := make(map[string]interface{})
                        test_ex["test"] = "hello"

                        for {
                                lk.Lock()
                                reqNum++
                                lk.Unlock()
                                logger.Println("ST start")
                                ready, err := st.Start(param, test_ex)
                                if err != nil {
                                        lk.Lock()
                                        fail++
                                        lk.Unlock()
                                        st.Shutdown()
                                        continue
                                }

                                err = waitReady(ready, logger)
                                if err != nil {
                                        lk.Lock()
                                        fail++
                                        lk.Unlock()
                                        st.Shutdown()
                                        continue
                                }

                                for _, data := range buffers.Data {
                                        if data != nil {
                                                st.SendAudioData(data.Data)
                                                time.Sleep(10 * time.Millisecond)
                                        }
                                }

                                logger.Println("send audio done")
                                ready, err = st.Stop()
                                if err != nil {
                                        lk.Lock()
                                        fail++
                                        lk.Unlock()
                                        st.Shutdown()
                                        continue
                                }

                                err = waitReady(ready, logger)
                                if err != nil {
                                        lk.Lock()
                                        fail++
                                        lk.Unlock()
                                        st.Shutdown()
                                        continue
                                }

                                logger.Println("SR done")
                                st.Shutdown()
                        }
                }(i)
        }

        wg.Wait()
}

func main() {
        coroutineId := flag.Int("num", 1, "coroutine number")
        flag.Parse()
        log.Default().Printf("start %d coroutines", *coroutineId)

        c := make(chan os.Signal, 1)
        signal.Notify(c, os.Interrupt)
        go func() {
                for range c {
                        lk.Lock()
                        log.Printf(">>>>>>>>REQ NUM: %d>>>>>>>>>FAIL: %d", reqNum, fail)
                        lk.Unlock()
                        os.Exit(0)
                }
        }()
        testMultiInstance(*coroutineId)
}