当我尝试通过HttpWebRequest上传音频文件时,Hololens应用程序卡住了


private void Upload(){
string apiURL = Globals.GoogleSpeechToTextURL + Globals.GoogleSpeechToTextApiKey;
string Response;
Debug.Log("Uploading " + filePath);
var fileInfo = new System.IO.FileInfo(filePath);
Debug.Log("Size: "+fileInfo.Length);
gtext.text = fileInfo.Length + " ";
Response = HttpUploadFile(apiURL, filePath, "file", "audio/wav; rate=44100");
var list = new List<Event>();
JObject obj = JObject.Parse(Response);
//return event array
var token = (JArray)obj.SelectToken("results");
if (token != null)
{
foreach (var item in token)
{
string json = JsonConvert.SerializeObject(item.SelectToken("alternatives")[0]);
list.Add(JsonConvert.DeserializeObject<Event>(json));
}
Debug.Log("Response String: " + list[0].transcript);
}
}
public string HttpUploadFile(string url, string file, string paramName, string contentType)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
Debug.Log(string.Format("Uploading {0} to {1}", file, url));
Byte[] bytes = File.ReadAllBytes(file);
String file64 = Convert.ToBase64String(bytes,
Base64FormattingOptions.None);
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ "config": { "languageCode" : "en-US" }, "audio" : { "content" : "" + file64 + ""}}";
// Debug.Log(json);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
//  Debug.Log(httpResponse);
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
catch (WebException ex)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
// Debug.Log(resp);
}
return "empty";
}

这是我用来上传音频文件的代码。当调用HttpUploadFile时,应用会暂停并显示黑屏一秒钟,然后继续。我尝试通过协程调用Upload函数,还尝试了从另一个线程使用 Unity API 或在主线程中调用函数。但它在上传时仍然会暂停。文件大小约为200 KB

我还能尝试什么来避免这个问题?

改用UnityWebRequest。您无法在主线程上进行阻塞 HTTP 请求调用。

此外,HTTP API 具有文件上传模式,如果字符串太大,将音频文件打包到 JSON 中的基本 64 编码字段中会使 JSON 解析器崩溃。

最新更新