Go SDK

最近更新时间:2024-07-01 15:10:32

我的收藏

安装依赖环境

Go1.9 版本及以上(如使用 go mod 需要 Go 1.14),Golang官网

安装 SDK

使用 Go Modules 模式安装

使用go mod init 来初始化项目。
go env -w GO111MODULE=auto //启用module mode,通过go.mod来管理包
go mod init xxx // 初始化项目
使用go get安装 Go SDK,可以选择安装所有依赖或本产品相关依赖。更多内容前往 Github 或者 Gitee 。
所有依赖
相关依赖
go get -v -u github.com/tencentcloud/tencentcloud-sdk-go
go get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/soe github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sts

使用 GOPATH 模式安装

使用 go get 安装 Go SDK,只能安装所有依赖。更多内容前往 Github 或者 Gitee 。
go get -v -u github.com/tencentcloud/tencentcloud-sdk-go

使用 SDK

可通过 控制台 生成代码进行调用或者参考下方示例,密钥获取可参考 快速入门

本地音频文件评测

发音数据传输附带初始化:直接调用 发音数据传输接口附带初始化过程 完成一次性评测。
package main

import (
b64 "encoding/base64"
"fmt"
"io/ioutil"
"os"

uuid "github.com/satori/go.uuid"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
soe "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/soe/v20180724"
)

func main() {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
credential := common.NewCredential(
"SecretId",
"SecretKey",
)
// 实例化soe的client对象
client, _ := soe.NewClient(credential, regions.Guangzhou, profile.NewClientProfile())

// 实例化发音数据传输接口请求对象
request := soe.NewTransmitOralProcessWithInitRequest()

// 请求参数赋值
filepath := ""
dat, err := ioutil.ReadFile(filepath) //本地音频地址
sEnc := b64.StdEncoding.EncodeToString(dat) //文件转base64
//获取uuid
sessionid := uuid.Must(uuid.NewV4()).String()
request.SeqId = common.Int64Ptr(1)
request.IsEnd = common.Int64Ptr(1)
request.VoiceFileType = common.Int64Ptr(3)
request.VoiceEncodeType = common.Int64Ptr(1)
request.UserVoiceData = common.StringPtr(sEnc)
request.SessionId = common.StringPtr(sessionid)
request.RefText = common.StringPtr("hello")
request.WorkMode = common.Int64Ptr(0)
request.EvalMode = common.Int64Ptr(0)
request.ScoreCoeff = common.Float64Ptr(1)

// 通过client对象调用TransmitOralProcessWithInit方法发起请求
response, err := client.TransmitOralProcessWithInit(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
// 输出json格式的字符串回包
fmt.Printf("%s", response.ToJsonString())
}

评测超时处理

如果本地文件过大,可能会导致评测超时。可以选用如下方案:
1. 流式分片传输:将发音数据进行分片处理,减少每次评测的时间。
2. 异步查询:使用异步功能将发音数据先上传,然后使用查询功能查询结构。
流式分片传输
异步查询
package main

import (
b64 "encoding/base64"
"fmt"
"io/ioutil"
"math"
"os"

uuid "github.com/satori/go.uuid"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
soe "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/soe/v20180724"
)

func main() {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
credential := common.NewCredential(
"SecretId",
"SecretKey",
)
// 实例化soe的client对象
client, _ := soe.NewClient(credential, regions.Guangzhou, profile.NewClientProfile())

// 实例化发音数据传输接口请求对象
request := soe.NewTransmitOralProcessWithInitRequest()

// 请求参数赋值
//获取uuid
sessionid := uuid.Must(uuid.NewV1()).String()
filepath := "SOEMUSIC/apple.mp3"
slice_num := 100 * 1024 // 分片大小
dat, err := ioutil.ReadFile(filepath) //本地音频地址
if err != nil {
panic(err)
}
dat_len := len(dat)
var send_content []byte
var IsEnd int64

var pkg = dat_len / slice_num
var pkg_num int = int(math.Ceil(float64(pkg)))

for j := 1; j <= pkg_num; j++ {
if j == pkg_num {
send_content = dat[(j-1)*slice_num : dat_len]
IsEnd = 1
} else {
send_content = dat[(j-1)*slice_num : j*slice_num]
IsEnd = 0
}
sEnc := b64.StdEncoding.EncodeToString(send_content) //文件转base64

request.SeqId = common.Int64Ptr(int64(j))
request.IsEnd = common.Int64Ptr(IsEnd)
request.VoiceFileType = common.Int64Ptr(3)
request.VoiceEncodeType = common.Int64Ptr(1)
request.UserVoiceData = common.StringPtr(sEnc)
request.SessionId = common.StringPtr(sessionid)
request.RefText = common.StringPtr("apple")
request.WorkMode = common.Int64Ptr(0)
request.EvalMode = common.Int64Ptr(0)
request.ScoreCoeff = common.Float64Ptr(1)

// 通过client对象调用TransmitOralProcessWithInit方法发起请求
response, err := client.TransmitOralProcessWithInit(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
// 输出json格式的字符串回包
fmt.Printf("%s", response.ToJsonString())
}

}

package main

import (
b64 "encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"time"

uuid "github.com/satori/go.uuid"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
soe "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/soe/v20180724"
)

func main() {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
credential := common.NewCredential(
"SecretId",
"SecretKey",
)
// 实例化soe的client对象
client, _ := soe.NewClient(credential, regions.Guangzhou, profile.NewClientProfile())


// 实例化发音数据传输接口请求对象
request := soe.NewTransmitOralProcessWithInitRequest()

// 请求参数赋值
filepath := "SOEMUSIC/para.mp3"
dat, err := ioutil.ReadFile(filepath) //本地音频地址
if err != nil {
fmt.Println( err)
}
sEnc := b64.StdEncoding.EncodeToString(dat) //文件转base64
//获取uuid
sessionid := uuid.Must(uuid.NewV4()).String()
request.WorkMode = common.Int64Ptr(1)
request.EvalMode = common.Int64Ptr(2)
request.ScoreCoeff = common.Float64Ptr(2.0)
request.SessionId = common.StringPtr(sessionid)
request.RefText = common.StringPtr("since")
request.IsAsync =common.Int64Ptr(1)
request.SeqId = common.Int64Ptr(1)
request.IsEnd = common.Int64Ptr(1)
request.SessionId = common.StringPtr(sessionid)
request.VoiceFileType = common.Int64Ptr(3)
request.VoiceEncodeType = common.Int64Ptr(1)
request.UserVoiceData = common.StringPtr(sEnc)

for i := 0; i <= 60; i++ {

// 通过client对象调用TransmitOralProcessWithInit方法发起请求
request.SetHttpMethod("POST")
transresponse, transerr := client.TransmitOralProcessWithInit(request)
if _, ok := transerr.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", transerr)
return
}
if transerr != nil {
panic(transerr)
}
// 输出json格式的字符串回包
fmt.Printf("%s", transresponse.ToJsonString())

var res interface{}
err := json.Unmarshal([]byte(transresponse.ToJsonString()), &res)
if err != nil {
fmt.Println("反序列化失败", err)
}
resmap, ok := res.(map[string]interface{})
fmt.Println(transresponse.ToJsonString())
status := resmap["Response"].(map[string]interface{})["Status"]
if !ok {
fmt.Println("DO SOMETHING!")
return
}
if status == "Finished" {
break
} else {
request.IsQuery = common.Int64Ptr(1)
time.Sleep(1000 * time.Millisecond)
}
}
}


使用方法说明

1. SessionID:使用 uuid 来作为 SessionID,用于区分不同的音频。
2. base64转换:读取本地音频文件,转换成 base64 数据进行评测。
3. 流式分片 base64 转换:读取本地音频文件,将音频进行分片,转换成 base64数据进行评测。
4. 异步轮询:使用 json 反序列化,获取评测结果,判断是否查询到最终结果。
SessionID
base64转换
流式分片
异步轮询
import (
"github.com/satori/go.uuid"
)
sessionid := uuid.Must(uuid.NewV4()).String()
import (
b64 "encoding/base64"
"io/ioutil"
)
dat, err := ioutil.ReadFile("") //本地音频地址
sEnc := b64.StdEncoding.EncodeToString(dat)
import (
b64 "encoding/base64"
"io/ioutil"
"math"
)
   
filepath := "SOEMUSIC/apple.mp3"
slice_num := 1 * 1024 // 分片大小
dat, err := ioutil.ReadFile(filepath) //本地音频地址
if err != nil {
panic(err)
}
dat_len := len(dat)
var send_content []byte
var IsEnd int64

var pkg = dat_len / slice_num
var pkg_num int = int(math.Ceil(float64(pkg)))

for j := 1; j <= pkg_num; j++ {
if j == pkg_num {
send_content = dat[(j-1)*slice_num : dat_len]
IsEnd = 1
} else {
send_content = dat[(j-1)*slice_num : j*slice_num]
IsEnd = 0
}
sEnc := b64.StdEncoding.EncodeToString(send_content) //文件转base64
}
for i := 0; i <= 60; i++ {

// 通过client对象调用TransmitOralProcessWithInit方法发起请求
request.SetHttpMethod("POST")
transresponse, transerr := client.TransmitOralProcessWithInit(request)
if _, ok := transerr.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", transerr)
return
}
if transerr != nil {
panic(transerr)
}
// 输出json格式的字符串回包
fmt.Printf("%s", transresponse.ToJsonString())

var res interface{}
err := json.Unmarshal([]byte(transresponse.ToJsonString()), &res)
if err != nil {
fmt.Println("反序列化失败", err)
}
resmap, ok := res.(map[string]interface{})
fmt.Println(transresponse.ToJsonString())
status := resmap["Response"].(map[string]interface{})["Status"]
if !ok {
fmt.Println("DO SOMETHING!")
return
}
if status == "Finished" {
break
} else {
request.IsQuery = common.Int64Ptr(1)
time.Sleep(1000 * time.Millisecond)
}
}

临时授权凭证

客户端 SDK 需要使用 获取联合身份临时访问凭证 生成临时密钥,保障密钥安全性。
package main

import (
"fmt"
"os"

"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
sts "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sts/v20180813"
)

func main() {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
credential := common.NewCredential(
"SecretId",
"SecretKey",
)
client, _ := sts.NewClient(credential, regions.Guangzhou, profile.NewClientProfile())
request := sts.NewGetFederationTokenRequest()

request.Name = common.StringPtr("soe")
request.Policy = common.StringPtr("{\\"version\\": \\"2.0\\",\\"statement\\": {\\"effect\\": \\"allow\\", \\"action\\": [\\"soe:TransmitOralProcessWithInit\\"], \\"resource\\": \\"*\\"}}")

response, err := client.GetFederationToken(request)
fmt.Println(err)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
fmt.Printf("%s", response.ToJsonString())
}