【发布时间】:2019-12-03 03:57:57
【问题描述】:
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函数,也试过这个Use Unity API from another Thread or call a function in the main Thread。但是在上传时它仍然暂停。文件大小约为200 KB
还有什么办法可以避免这个问题?
【问题讨论】:
-
协程仍在主线程中执行.. 如果使用协程,请选择
UnityWebRequest。这里的主要问题是GetResponse()是一个阻塞调用。你能告诉我们你是如何尝试在一个线程中做到这一点的吗?我的猜测是您根本没有在另一个线程中启动它,而是在统一主线程中启动它......
标签: c# http unity3d networking audio