使用语音与用户进行交互则最基础的部分应该具有语音合成的功能,目前百度AI平台提供的语音合成服务是很好的解决方案。
首先到百度AI官网申请创建语音合成应用,地址http://ai.baidu.com/tech/speech/tts
文章图片
下载SDK地址http://ai.baidu.com/sdk
文章图片
文章图片
按照官网给出的技术文档对百度语音API进行调用
Demo:
文章图片
在unity3d中使用百度语音
首先将SDK中的动态链接库文件添加到unity项目引用中
在添加过程中由于在之前进行过通过百度api进行人脸识别,已导入过百度AI的SDK 再次导入版本不同会导致同名链接库文件出现冲突,直接使用3.3.1版本的动态链接库文件开发即可。
完整版封装可直接调用的类文件:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
public class aduio : MonoBehaviour {private const string lan = "zh";
private const string per = "1";
private const string ctp = "1";
private const string spd = "4";
private const string pit = "6";
private const string vol = "9";
private const string cuid = "00-12-7B-16-74-8D";
publicstring tex = "";
private const string tok = "24.0d92efd41bbb50b9c910654e7bbf600d.2592000.1523522687.282335-9900430";
private const string rest = "tex={0}&lan={1}&per={2}&ctp={3}&cuid={4}&tok={5}&spd={6}&pit={7}&vol={8}";
private const int NULL = 0, ERROR_SUCCESS = NULL;
[System.Runtime.InteropServices.DllImport("WinMm.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
public aduio(string tex) {
this.tex = tex;
}public void creatMp3(string strFilename)
{
string strUpdateData = https://www.it610.com/article/string.Format(rest, tex, lan, per, ctp, cuid, tok, spd, pit, vol);
HttpWebRequest req = WebRequest.Create("http://tsn.baidu.com/text2audio") as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = Encoding.UTF8.GetByteCount(strUpdateData);
using (StreamWriter sw = new StreamWriter(req.GetRequestStream()))
sw.Write(strUpdateData);
HttpWebResponse res = req.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = res.GetResponseStream();
//创建本地文件写入流
Stream stream = new FileStream(Application.streamingAssetsPath + "//Ogg//"+ strFilename + ".mp3", FileMode.Create);
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, (int)bArr.Length);
while (size > 0)
{
stream.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, (int)bArr.Length);
}
stream.Close();
responseStream.Close();
}
}
调用:
aduio a = new aduio("欢迎进入英语学习系统,如果你准备好了请说开始");
strFilname = Guid.NewGuid().ToString();
a.creatMp3(strFilname);
string strMp3 = "//Ogg//" + strFilname + ".mp3";
string strWav = "//Ogg//" + strFilname + ".wav";
StartCoroutine(LoadMusic(Application.streamingAssetsPath + strMp3, Application.streamingAssetsPath + strWav));
【【英语学习系统】使用百度API进行在线文字换语音,语音合成】