Go SDK

更新时间:
复制 MD 格式

This topic describes how to use the Go software development kit (SDK) for Alibaba Cloud Voice Service. It includes instructions for installing the SDK and code examples.

Prerequisites

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

Download and installation

Note
  • The SDK supports Go 1.16 and later.

  • Make sure that you have installed the Go environment and completed the basic configuration.

  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

When you use an Akid and Akkey to obtain a token, you must cache the token and update it based on the time-to-live (TTL) parameter that is returned. Do not frequently call the API operation to obtain a token. If you do, throttling may be triggered.

1. ConnectionConfig

Contains the basic parameters for establishing a connection.

Parameters:

Parameter

Type

Description

Url

String

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

Token

String

The access token. For more information, see Overview of how to 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.

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

Creates a `ConnectionConfig` object from a URL, AppKey, and token.

  • Parameters:

Parameter

Type

Description

Url

String

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

Appkey

String

The AppKey of the project.

Token

String

The access token. For more information, see Overview of how to obtain a token.

  • Return value:

*ConnectionConfig: A pointer to the connection configuration object.

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

You can specify connection parameters as a JSON string.

  • Parameters:

Parameter

Type

Description

jsonStr

String

A JSON string that describes the connection parameters. Valid fields are 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.

Speech synthesis

1. SpeechSynthesisStartParam

Contains the parameters for real-time speech synthesis.

Parameter

Type

Description

Voice

String

The voice. The default value is "xiaoyun".

Format

String

The audio format. The default value is WAV.

SampleRate

Integer

The sample rate. The default value is 16000 Hz.

Volume

Integer

The volume. The value ranges from 0 to 100. The default value is 50.

SpeechRate

Integer

The speech rate. The value ranges from -500 to 500. The default value is 0.

PitchRate

Integer

The pitch. The value ranges from -500 to 500. The default value is 0.

EnableSubtitle

Boolean

Specifies whether to enable the captioning feature. The default value is false.

  • true: enables the feature.

  • false: disables the feature.

2. func DefaultSpeechSynthesisParam() SpeechSynthesisStartParam

Creates a `SpeechSynthesisStartParam` object with default values.

  • Parameters: None.

  • Return value:

    SpeechSynthesisStartParam: An object that contains the default parameters.

3. func NewSpeechSynthesis(...) (*SpeechSynthesis, error)

Creates a new `SpeechSynthesis` object.

  • Parameters:

Parameter

Type

Description

config

*ConnectionConfig

For more information, see the Establish a connection section.

logger

*NlsLogger

For more information, see the SDK logs section.

realtimeLongText

Boolean

  • false: short text.

  • true: real-time long text.

taskfailed

func(string, interface{})

The callback parameter for handling errors during the synthesis process. `interface{}` is a custom user parameter.

synthesisresult

func([]byte, interface{})

The callback parameter for speech synthesis data.

metainfo

func(string, interface{})

The callback for caption data. This requires the EnableSubtitle parameter to be set to true.

completed

func(string, interface{})

The callback parameter for when synthesis is complete.

closed

func(interface{})

The callback parameter for when the connection is closed.

param

interface{}

A custom user parameter.

  • Return value: None.

4. func (tts *SpeechSynthesis) Start(text string, param SpeechSynthesisStartParam, extra map[string]interface{}) (chan bool, error)

Performs speech synthesis on the specified text using the specified parameters.

  • Parameters:

Parameter

Type

Description

text

String

The text to synthesize.

Note

To call the multi-emotion feature of a voice, add the ssml-emotion tag to the text. For more information, see <emotion>.

If you use the <emotion> tag for a voice that does not support multiple emotions, the `Illegal ssml text` error is reported.

param

SpeechRecognitionStartParam

The real-time synthesis parameters.

extra

map[string]interface{}

Additional key:value parameters.

  • Return value:

    • chan bool: A pipeline that sends a notification when speech synthesis is complete.

    • error: A fault or an abnormal condition.

5. func (tts *SpeechSynthesis) Shutdown()

Forcibly stops speech synthesis.

  • Parameters: None.

  • Return value: None.

SDK logs

1. func DefaultNlsLog() *NlsLogger

Creates a global default log object. By default, the log object uses NLS as the prefix and outputs logs 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.

  • Parameters:

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)

Sets whether to output the log to the corresponding io.Writer.

  • Parameters:

Parameter

Type

Description

sil

Boolean

Specifies whether to disable log output.

  • true: Prohibited.

  • false: Allowed.

  • Return value: None.

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

Sets whether to print debug logs. This setting affects only logs that are output using the `Debugf` or `Debugln` method.

  • Parameters:

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.

  • Parameters:

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 entry.

  • Parameters:

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 log properties.

  • Parameters:

Parameter

Type

Description

flags

Integer

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

  • Return value: None.

8. Log printing

Log printing methods:

Method name

Description

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

Prints a standard log.

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

Prints a standard log. A new line is automatically added at the end of the entry.

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

Prints a formatted standard log. For more information about the format, see the official Go documentation.

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

Prints a debug log. A new line is automatically added at the end of the entry.

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

Prints a formatted debug log.

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

Prints a fatal error log. The process then exits.

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

Prints a fatal error log. A new line is automatically added at the end of the entry. The process then exits.

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

Prints a formatted fatal error log. The process then exits.

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

Prints a fatal error log and then panics. The process exits and prints the crash information.

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

Prints a fatal error log and then panics. A new line is automatically added at the end of the entry. The process exits and prints the crash information.

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

Prints a formatted fatal error log and then panics. The process exits and prints the crash information.

Code example

package main

import (
  "errors"
  "io"
  "log"
  "os"
  "sync"
  "time"

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

const (
  //online key
  APPKEY = "Your APPKEY" // To obtain an AppKey, go to the console: https://nls-portal.console.aliyun.com/applist
  TOKEN  = "Your TOKEN"  // For information about how to obtain a token, see: https://help.aliyun.com/document_detail/450514.html
)

type TtsUserParam struct {
  F      io.Writer
  Logger *nls.NlsLogger
}

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

  p.Logger.Println("TaskFailed:", text)
}

func onSynthesisResult(data []byte, param interface{}) {
  p, ok := param.(*TtsUserParam)
  if !ok {
    log.Default().Fatal("invalid logger")
    return
  }
  p.F.Write(data)
}

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

  p.Logger.Println("onCompleted:", text)
}

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

  p.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(60 * time.Second):
    {
      logger.Println("Wait timeout")
      return errors.New("wait timeout")
    }
  }
  return nil
}

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

const (
  TEXT = "Hello, Xiaode. How is the weather today?"
)

func testMultiInstance() {
  param := nls.DefaultSpeechSynthesisParam()
  config := nls.NewConnectionConfigWithToken(nls.DEFAULT_URL, APPKEY, TOKEN)
  strId := "ID0"
  fname := "tts_dump.wav"
  ttsUserParam := new(TtsUserParam)
  fout, err := os.OpenFile(fname, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0666)
  logger := nls.NewNlsLogger(os.Stderr, strId, log.LstdFlags|log.Lmicroseconds)
  logger.SetLogSil(false)
  logger.SetDebug(true)
  logger.Printf("Test Normal Case for SpeechSynthesis:%s", strId)
  ttsUserParam.F = fout
  ttsUserParam.Logger = logger
  // The third parameter specifies whether to request long-text speech synthesis. false indicates short-text speech synthesis.
  tts, err := nls.NewSpeechSynthesis(config, logger, false,
    onTaskFailed, onSynthesisResult, nil,
    onCompleted, onClose, ttsUserParam)
  if err != nil {
    logger.Fatalln(err)
    return
  }

  lk.Lock()
  reqNum++
  lk.Unlock()
  logger.Println("TTS start")
  ch, err := tts.Start(TEXT, param, nil)
  if err != nil {
    lk.Lock()
    fail++
    lk.Unlock()
    tts.Shutdown()
  }

  err = waitReady(ch, logger)
  if err != nil {
    lk.Lock()
    fail++
    lk.Unlock()
    tts.Shutdown()
  }
  logger.Println("Synthesis done")
  tts.Shutdown()

}

func main() {
  testMultiInstance()
}

FAQ

Why does the "websocket: bad handshake" error occur?

This error indicates that the connection to the server failed. Verify that the Token and AppKey are set correctly.