最佳实践 | 用腾讯云智能语音打造智能对话机器人

在AI技术的推动下,智能对话机器人逐渐成为我们工作、生活中的重要效率工具,乃至是伙伴,特别是为企业带来最原始最直观的“降本增效”落地实现。

作为开发者,你是否有想过基于语音技术打造一款智能对话机器人呢?

本文将可以手把手教你技术实现细节。

首先我们分析下智能对话机器人需要些什么东西:

1.语音输入:想要智能对话肯定需要语音的输入,输出。

2.语音识别:将语音识别成文字。

3.智能问答服务:将语音识别结果,输入该服务,并得到结果。

4.语音合成:将智能问答服务回答生成音频

5.语音播报:将智能问答服务回答的问题,用语音的形式播报给您听。

流程图:

语音采集:

1.使用腾讯云语音识别提供的SDK(安卓,IOS,微信小程序)

2.可以自行使用硬件录音设备采集音频

3.自己在端上(IOS,安卓等)调起录音设备采集音频

 

技术流程:

1.先采集音频

2.用音频流数据调用腾讯云语音识别(ASR)

3.将语音识别的文本数据调用智能问答服务

4.使用智能问答服务的回答调用腾讯云语音合成(TTS)

5.最后将语音合成产生的音频返回给端上播放

一、准备工作

1.1开通语音识别服务

笔者使用的是腾讯的语音识别,先开通一下服务,点这里 腾讯云语音识别控制台 , 点击立即开通就能开通服务了。

可以点击这里领取一个新人的体验资源包: 语音识别_实时语音识别_录音文件识别_语音转文本服务 - 腾讯云

1.2获取调用服务的API密钥

访问腾讯云的服务,都需要一个秘钥,在腾讯云访问管理的 API密钥管理页面 ,可以新建一个秘钥,这个可一定要保管好,不能泄露出去,不然就被别人盗用了。秘钥后面我们要用到。

1.3获取语音识别,语音合成SDK

语音识别SDK获取:语音识别 实时语音识别(websocket)-API 文档-文档中心-腾讯云

语音合成SDK获取:语音合成 基础语音合成-API 文档-文档中心-腾讯云

端SDK获取:

1.IOS:登录 - 腾讯云

2.安卓:登录 - 腾讯云

3.微信小程序:腾讯云智能语音 | 小程序插件 | 微信公众平台

1.4、接入智能问答服务 

WeLM:- WeLM

这里也可以使用别的智能问答服务,比如ChatGPT

二、代码开发

逻辑包含:

1.请求ASR实时识别

2.请求智能问答服务

3.请求TTS语音合成,获取音频

代码编译:

1.执行命令生成go.mod环境 go mod init demo

2.go build 编译

3.执行 ./demo -e 16k_zh -f 测试音频地址 -format 1

注:本代码只包含了服务端部分,可以自行接入SDK将音频流传到服务端识别。

package main

import (
	"encoding/base64"
	"flag"
	"fmt"
	ttsCommon "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"
	tts "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tts/v20190823"
	"github.com/tencentcloud/tencentcloud-speech-sdk-go/asr"
	"github.com/tencentcloud/tencentcloud-speech-sdk-go/common"
	"os"
	"sync"
	"time"
)

var (
	AppID           = "输入appid"
	SecretID        = "输入密钥ID"
	SecretKey       = "输入密钥key"
	EngineModelType = "16k_zh"
	SliceSize       = 16000
)

// MySpeechRecognitionListener implementation of SpeechRecognitionListener
type MySpeechRecognitionListener struct {
	ID int
}

// OnRecognitionStart implementation of SpeechRecognitionListener
func (listener *MySpeechRecognitionListener) OnRecognitionStart(response *asr.SpeechRecognitionResponse) {
}

// OnSentenceBegin implementation of SpeechRecognitionListener
func (listener *MySpeechRecognitionListener) OnSentenceBegin(response *asr.SpeechRecognitionResponse) {
}

// OnRecognitionResultChange implementation of SpeechRecognitionListener
func (listener *MySpeechRecognitionListener) OnRecognitionResultChange(response *asr.SpeechRecognitionResponse) {
}

// OnSentenceEnd implementation of SpeechRecognitionListener
func (listener *MySpeechRecognitionListener) OnSentenceEnd(response *asr.SpeechRecognitionResponse) {
	fmt.Printf("语音识别结果: %s \n", response.Result.VoiceTextStr)
	ConversationalRobot(response.Result.VoiceTextStr)
}

// OnRecognitionComplete implementation of SpeechRecognitionListener
func (listener *MySpeechRecognitionListener) OnRecognitionComplete(response *asr.SpeechRecognitionResponse) {
}

// OnFail implementation of SpeechRecognitionListener
func (listener *MySpeechRecognitionListener) OnFail(response *asr.SpeechRecognitionResponse, err error) {
	fmt.Printf("%s|%s|OnFail: %v\n", time.Now().Format("2006-01-02 15:04:05"), response.VoiceID, err)
}

var proxyURL string
var VoiceFormat *int
var e *string

func main() {
	var f = flag.String("f", "test.pcm", "audio file")
	var p = flag.String("p", "", "proxy url")
	VoiceFormat = flag.Int("format", 0, "voice format")
	e = flag.String("e", "", "engine_type")
	fmt.Println("input-", *e, "-input")
	flag.Parse()
	if *e == "" {
		panic("please input engine_type")
	}
	if *VoiceFormat == 0 {
		panic("please input voice format")
	}

	proxyURL = *p
	var wg sync.WaitGroup
	wg.Add(1)
	go processOnce(1, &wg, *f)
	fmt.Println("Main: Waiting for workers to finish")
	wg.Wait()
	fmt.Println("Main: Completed")

}

func processOnce(id int, wg *sync.WaitGroup, file string) {
	defer wg.Done()
	process(id, file)
}

func process(id int, file string) {
	audio, err := os.Open(file)
	defer audio.Close()
	if err != nil {
		fmt.Printf("open file error: %v\n", err)
		return
	}

	listener := &MySpeechRecognitionListener{
		ID: id,
	}
	credential := common.NewCredential(SecretID, SecretKey)
	EngineModelType = *e
	fmt.Println("engine_type:", EngineModelType)
	recognizer := asr.NewSpeechRecognizer(AppID, credential, EngineModelType, listener)
	recognizer.ProxyURL = proxyURL
	recognizer.VoiceFormat = *VoiceFormat
	err = recognizer.Start()
	if err != nil {
		fmt.Printf("%s|recognizer start failed, error: %v\n", time.Now().Format("2006-01-02 15:04:05"), err)
		return
	}

	data := make([]byte, SliceSize)
	//这里的data可以换成实时端上传输过来的音频流
	for n, err := audio.Read(data); n > 0; n, err = audio.Read(data) {
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			fmt.Printf("read file error: %v\n", err)
			break
		}
		//一句话识别结束会回调上面OnSentenceEnd方法
		err = recognizer.Write(data[0:n])
		if err != nil {
			break
		}
		time.Sleep(20 * time.Millisecond)
	}
	recognizer.Stop()
}

func ConversationalRobot(text string) {
	//调用智能问答服务,获取回答
	Result := SendToGPTService(text)
	//把智能问答服务的文案转成音频文件
	audioData := TextToVoice(Result)
	//将音频文件返回给端上播放
	ResponseAudioData(audioData)
}

func ResponseAudioData(audioData []byte) {
	//把音频数据audioData推到端上播放
}

func SendToGPTService(text string) string {
	// API 调用智能问答服务
	// 获取智能问答服务返回结果
	result := "智能问答服务返回结果"
	fmt.Println("智能问答服务 API调用")
	return result
}

func TextToVoice(text string) []byte {
	fmt.Println("语音合成调用")
	// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
	// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
	// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
	credential := ttsCommon.NewCredential(
		SecretID,
		SecretKey,
	)
	// 实例化一个client选项,可选的,没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "tts.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := tts.NewClient(credential, "ap-beijing", cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := tts.NewTextToVoiceRequest()

	request.Text = ttsCommon.StringPtr(text)
	request.SessionId = ttsCommon.StringPtr("f435g34d23a24y546g")

	// 返回的resp是一个TextToVoiceResponse的实例,与请求对象对应
	response, err := client.TextToVoice(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return nil
	}
	if err != nil {
		panic(err)
	}
	// 输出json格式的字符串回包
	audioData, _ := base64.StdEncoding.DecodeString(*response.Response.Audio)
	fmt.Println("语音合成调用结束")
	return audioData
}

以上就是智能语音对话机器人技术细节的实现,感兴趣的同学也可以实操或者进行拓展开发。

目前,智能对话机器人已经在客户触达、营销运营、窗口服务和人机对话交互等经济生产活动环节进入规模化落地阶段,随着AI技术的不断创新,智能对话机器人也将衍生出更高阶、更智能的模式。

腾讯云智能面向企业客户与开发者也提供了一站式的语音技术服务,更多产品信息也可以前往腾讯云官网了解。

腾讯云智能语音识别:语音识别_实时语音识别_录音文件识别_语音转文本服务 - 腾讯云

腾讯云智能语音合成:语音合成_语音定制_文本转语音服务 - 腾讯云

猜你喜欢

转载自blog.csdn.net/tencentAI/article/details/129831795