Go SDK
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 and configure Go 1.16 or later.
Obtain a project Appkey and prepare either an access token or an AccessKey pair for obtaining a token. For project configuration, see Manage projects. To obtain a token, see Obtain a token.
Review the audio requirements and service parameters in the short-sentence speech recognition API reference.
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_KEYandNLS_TOKENin the program's runtime environment. The example reads these variables throughos.Getenvfor 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
audioPathand 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 |
|
|
|
The WebSocket endpoint of the speech service. You can use |
|
|
|
The project Appkey. |
|
|
|
The access token. Required when initializing with a token. |
|
|
|
The AccessKey ID. Required together with |
|
|
|
The AccessKey secret. Required together with |
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 |
|
|
|
The audio format. You can use the |
|
|
|
The audio sample rate in Hz. It must match the audio and the project model. |
|
|
|
Specifies whether to return intermediate results. |
|
|
|
Specifies whether to enable punctuation prediction. |
|
|
|
Specifies whether to enable inverse text normalization (ITN), which can convert Chinese numbers to Arabic numerals. |
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 |
|
|
|
The connection configuration. See Connection settings. |
|
|
|
The logger. If |
|
|
|
The callback for |
|
|
|
The callback for |
|
|
|
The callback for |
|
|
|
The callback for |
|
|
|
The callback for a server notification that the connection is closed. When calling |
|
|
|
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 inkey:valueform. If a field has the same name as a field inparam, the value inextratakes precedence. Passnilif no additional parameters are needed.Return values:
errorindicates an error while initiating the request. Iferrorisnil, wait for the Boolean value on the returned channel.trueindicates that the task has started and audio can be sent.falseindicates 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 |
|
|
The SDK version identifier included in the request context. |
|
|
The PCM audio format. Value: |
|
|
The WAV audio format. Value: |
|
|
The OPUS audio format. Value: |
|
|
The OPU audio format. Value: |
|
|
The default region for obtaining tokens. Value: |
|
|
The default domain for obtaining tokens. Value: |
|
|
The API version for obtaining tokens. Value: |
|
|
The default WebSocket endpoint. Value: |
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 |
|
|
|
The log output destination. Any object that implements |
|
|
|
The log prefix. |
|
|
|
Log flags, such as date and time flags. See Go log constants. |
Configure logging
None of the following methods return a value.
|
Method |
Description |
|
|
|
|
|
|
|
|
Sets the log output destination. |
|
|
Sets the log prefix. |
|
|
Sets the log flags. See Go log constants. |
Write logs
|
Method |
Description |
|
|
Writes an ordinary log message. |
|
|
Writes an ordinary log message followed by a newline. |
|
|
Writes an ordinary log message using a format string. |
|
|
Writes a debug message followed by a newline. |
|
|
Writes a debug message using a format string. |
|
|
Writes a log message and calls |
|
|
Writes a log message followed by a newline, then calls |
|
|
Writes a formatted log message, then calls |
|
|
Writes a log message and triggers |
|
|
Writes a formatted log message and triggers |
For formatting rules, see the Go log documentation.