所以使用Wit.ai我尝试使用语音文本。我正在使用Github的Wit3D示例:https://github.com/afauch/wit3d/blob/master/Assets/UserScripts/Wit3D.cs
录制声音并保存到.wav文件就可以了。将请求发送到服务器不会。 .wav文件有效,因为我通过Postman手动发出请求时得到响应。
请求代码如下所示:
string GetJSONText(string file)
{
// get the file w/ FileStream
FileStream filestream = new FileStream(file, FileMode.Open, FileAccess.Read);
BinaryReader filereader = new BinaryReader(filestream);
byte[] BA_AudioFile = filereader.ReadBytes((Int32)filestream.Length);
filestream.Close();
filereader.Close();
//var bytes = File.ReadAllBytes(Path.Combine(Application.dataPath, "sample.wav"));
// create an HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.wit.ai/speech?v=20160901");
request.Method = "POST";
request.Headers["Authorization"] = "Bearer 3XFWDOBVS65V5A2VZWZFBB2PHOKDWGOH";
request.ContentType = "audio/wav";
//request.Timeout = 10000;
request.GetRequestStream().Write(BA_AudioFile, 0, BA_AudioFile.Length);
// Process the wit.ai response
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
print("Http went through ok");
StreamReader response_stream = new StreamReader(response.GetResponseStream());
return response_stream.ReadToEnd();
}
else
{
return "Error: " + response.StatusCode.ToString();
return "HTTP ERROR";
}
}
catch (Exception ex)
{
return "Error: " + ex.Message;
return "HTTP ERROR";
}
}
无论是否在请求中放置超时,我都会收到以下错误消息:"错误:请求超时"
删除该行:
request.GetRequestStream().Write(BA_AudioFile, 0, BA_AudioFile.Length)
会得到我的答复: 错误:获取响应流时出错(写入:身份验证或解密失败。) 这是有道理的,因为没有什么可以解密。 我的防火墙似乎不是问题所在。有关为什么会有超时的想法?使用不同的获取字节[]的方法也没有解决它。
编辑: 将代码放在普通的控制台应用程序中确实有效。所以这似乎是一个Unity问题。
答案 0 :(得分:1)
将此添加到您的脚本顶部:
using System.Collections.Generic;
使用此代码。
public void SendRequest(string wavPath)
{
if(!File.Exists(wavPath))
{
Debug.Log("Invalid wav path.");
return;
}
StartCoroutine(SendRequestToWitAi(wavPath));
}
public IEnumerator SendRequestToWitAi(string wavPath)
{
string API_KEY = "3XFWDOBVS65V5A2VZWZFBB2PHOKDWGOH";
string url = "https://api.wit.ai/speech?v=20160526";
byte[] postData = File.ReadAllBytes(wavPath);
Dictionary<string, string> headers = new Dictionary<string, string>();
headers["Content-Type"] = "audio/wav";
headers["Authorization"] = "Bearer " + API_KEY;
float timeSent = Time.time;
WWW www = new WWW(url, postData, headers);
yield return www;
while (!www.isDone)
{
yield return null;
}
float duration = Time.time - timeSent;
if (www.error != null && www.error.Length > 0)
{
Debug.Log("Error: " + www.error + " (" + duration + " secs)");
yield break;
}
Debug.Log("Success (" + duration + " secs)");
Debug.Log("Result: " + www.text);
}
使用JSON解析器解析www.text值。 “_text”字段包含结果文本。