0
    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";

            }

This is the code I am using to upload an audio file. When HttpUploadFile gets called, the app pauses and shows a black screen for a second and then continues. I tried calling Upload function through coroutine, and also tried this Use Unity API from another Thread or call a function in the main Thread. But still it pauses while uploading. The file size is around 200 KB

What else can I try to avoid this problem?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
MrRobot9
  • 2,402
  • 4
  • 31
  • 68
  • Can you look for asyn programming -- [http://www.stevevermeulen.com/index.php/2017/09/using-async-await-in-unity3d-2017/](http://www.stevevermeulen.com/index.php/2017/09/using-async-await-in-unity3d-2017/) – user1672994 Dec 03 '19 at 04:10
  • Coroutine is still executed in the main thread .. if using a Coroutine rather go for `UnityWebRequest`. The main issue here is that `GetResponse()` is a blocking call. Could you show us how you tried to do it in a thread? My guess would be that you simply didn't start it in another thread but in the unity main thread... – derHugo Dec 03 '19 at 06:14

1 Answers1

0

Use UnityWebRequest instead. You cannot make blocking HTTP request calls on the main thread.

Also, the HTTP API has a pattern for file uploads, packing an audio file into a base 64-encoded field in JSON is going to crash your JSON parser if the string is too large.

DoctorPangloss
  • 2,994
  • 1
  • 18
  • 22