enver yumrutas Ответов: 0

Unity speech to text ошибка Google cloud:502


Geciçi Mav dosyası yüklenirken hata oluştu: System.Net.WebException: The remote server returned an error: (502) Broken pipe.
  at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000] in <filename unknown>:0 
  at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00000] in <filename unknown>:0 
UnityEngine.Debug:Log(Object)
GoogleVoiceSpeech:HttpUploadFile(String, String, String, String) (at Assets/Scripts/GoogleVoiceSpeech.cs:166)
GoogleVoiceSpeech:OnGUI() (at Assets/Scripts/GoogleVoiceSpeech.cs:104)


Что я уже пробовал:

using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Net;

[RequireComponent (typeof (AudioSource))]

public class GoogleVoiceSpeech : MonoBehaviour {

		public GUIText TextBox;

		struct ClipData
		{
				public int samples;
		}

		const int HEADER_SIZE = 44;

		private int minFreq;
		private int maxFreq;

		private bool micConnected = false;

        //Ekli AudioSource'un değişkeni
        private AudioSource goAudioSource;

		public string apiKey;

	// Başlangıç gerçekleştirilecek işlemler
	void Start () {
				//Mikrofon bağlantı kontrolü
				if(Microphone.devices.Length <= 0)
				{
						//Mikrofona bağlı değilse verilecek uyarı mesajı
						Debug.LogWarning("Mikrofon bağlı değil!");
				}
				else //Mikrofon var ise
				{
						// micConnected değişkeni true atanır
						micConnected = true;

						// Bağlantının olduğu mikrofonun kayıt özellikleri çağrılır
						Microphone.GetDeviceCaps(null, out minFreq, out maxFreq);

                //Belgelere göre, minFreq ve maxFreq sıfır ise, mikrofon herhangi bir frekansı destekler ...
                if (minFreq == 0 && maxFreq == 0)
						{
								// Kayıt frekansı 44100 hz
								maxFreq = 44100;
						}

						//Ekli olan AudioSource birleşeni
						goAudioSource = this.GetComponent<AudioSource>();
				}
	}

		void OnGUI() 
		{
        // Mikrofon varsa " micConnected==true"
        if (micConnected)
				{
						// Mikrofondan ses kaydedilmiyorsa
						if(!Microphone.IsRecording(null))
						{
								// Kayıt butonuna basıldığında gerçekleştirilenler
								if(GUI.Button(new Rect(Screen.width/2-100, Screen.height/2-25, 200, 50), "Kayıt"))
								{
										// Kayıt başlatılır ve ses kaydedilir
										goAudioSource.clip = Microphone.Start( null, true, 7, maxFreq); // Ses kayıt süresi 7 sn olarak ayarlanmıştır
								}
						}
						else //Kayıt devam ediyorsa
						{
								
								// Başlat ve durdur butonuna basıldığında 
								if(GUI.Button(new Rect(Screen.width/2-100, Screen.height/2-25, 200, 50), "Durdur ve Başlat"))
								{
										float filenameRand = UnityEngine.Random.Range (0.0f, 10.0f);

										string filename = "test" + filenameRand;

										Microphone.End(null); // Ses kaydını durdur

										Debug.Log( "Kayıt durduruldu");

										if (!filename.ToLower().EndsWith(".wav")) {
												filename += ".wav";
										}

										var filePath = Path.Combine("testing/", filename);
										filePath = Path.Combine(Application.persistentDataPath, filePath);
										Debug.Log("Kaydedilen dosya yolu: " + filePath);
                                        // Kullanıcı kayıt durum kontrolü										
										Directory.CreateDirectory(Path.GetDirectoryName(filePath));
										SavWav.Save (filePath, goAudioSource.clip); //Geçici Mav türünce dosya kaydının gerçekleştiği satır
										Debug.Log( "Kaydediliyor @ " + filePath);
										string apiURL = "http://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key=" + apiKey;
										string Response;

										Debug.Log( "Yükleme " + filePath);
										Response = HttpUploadFile (apiURL, filePath, "file", "audio/wav; rate=44100");
										Debug.Log ("Yanıt: " +Response);

										var jsonresponse = SimpleJSON.JSON.Parse(Response);

										if (jsonresponse != null) {		
												string resultString = jsonresponse ["Sonuç"] [0].ToString ();
												var jsonResults = SimpleJSON.JSON.Parse (resultString);

												string transcripts = jsonResults ["alternatif"] [0] ["Kayıt bilgisi"].ToString ();

												Debug.Log ("Kayıt bilgisi: " + transcripts );
												TextBox.text = transcripts;

										}
										

										File.Delete(filePath); //Geçici Mav dosyasının silindiği satır
									
								}

								GUI.Label(new Rect(Screen.width/2-100, Screen.height/2+25, 200, 50), "Kayıt devam ediyor...");
						}
				}
				else // Mikrofon yoksa
				{
						//Kırmızı uyarı "Mikrofon bağlı değil!" ekrandaki mesaj
						GUI.contentColor = Color.red;
						GUI.Label(new Rect(Screen.width/2-100, Screen.height/2-25, 200, 50), "Mikrofona bağlı değil ");
				}
		}

		public string HttpUploadFile(string url, string file, string paramName, string contentType) {
				Debug.Log(string.Format("Yükleniyor {0} to {1}", file, url));
				HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
				wr.ContentType = "audio/l16; rate=44100";
				wr.Method = "POST";
		 		wr.KeepAlive = true;
                wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
                // wr.UseDefaultCredentials = true;
                // wr.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                Stream rs = wr.GetRequestStream();
				FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
				byte[] buffer = new byte[4096];
				int bytesRead = 0;
				while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) {
						rs.Write(buffer, 0, bytesRead);
				}
				fileStream.Close();
				rs.Close();

				WebResponse wresp = null;
				try {
						wresp = wr.GetResponse();
						Stream stream2 = wresp.GetResponseStream();
						StreamReader reader2 = new StreamReader(stream2);

						string responseString =  string.Format("{0}", reader2.ReadToEnd());
						Debug.Log("HTTP " +responseString);
						return responseString;

				} catch(Exception ex) {
						Debug.Log(string.Format("Geciçi Mav dosyası yüklenirken hata oluştu: {0}", ex));
						if(wresp != null) {
								wresp.Close();
								wresp = null;
								return "Error";
						}
				} finally {
						wr = null;
			
				}

				return "empty";
		}
	

}

0 Ответов