智慧.ai超时c# Unity
本文关键字:Unity 超时 ai 智慧 | 更新日期: 2023-09-27 18:05:03
我在试着用语音发短信。我使用的Wit3D的例子从Github: 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的问题。
添加到脚本顶部:
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"字段包含结果文本。