Hasli4

Untitled

Apr 24th, 2026
236
0
Never
5
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.30 KB | None | 0 0
  1. IEnumerator StartMicRoutineSafe()
  2. {
  3.     if (micStarted)
  4.         yield break;
  5.  
  6.     if (statusText)
  7.         statusText.text = "Инициализирую микрофон...";
  8.  
  9.     // даём системе немного времени после закрытия окна разрешения
  10.     yield return null;
  11.     yield return new WaitForSecondsRealtime(0.25f);
  12.  
  13.     // ждём, пока приложение реально снова активно
  14.     while (!Application.isFocused)
  15.         yield return null;
  16.  
  17. #if UNITY_ANDROID
  18.     if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
  19.     {
  20.         if (statusText)
  21.             statusText.text = "Нет доступа к микрофону";
  22.         yield break;
  23.     }
  24. #endif
  25.  
  26.     if (Microphone.devices.Length == 0)
  27.     {
  28.         // не сдаёмся сразу, а ждём немного
  29.         float waitTime = 2f;
  30.         while (Microphone.devices.Length == 0 && waitTime > 0f)
  31.         {
  32.             waitTime -= Time.unscaledDeltaTime;
  33.             yield return null;
  34.         }
  35.  
  36.         if (Microphone.devices.Length == 0)
  37.         {
  38.             if (statusText)
  39.                 statusText.text = "Микрофон не обнаружен";
  40.             Debug.Log("Microphone not found after waiting");
  41.             yield break;
  42.         }
  43.     }
  44.  
  45.     micDevice = string.IsNullOrEmpty(microphoneDevice) ? Microphone.devices[0] : microphoneDevice;
  46.  
  47.     micClip = Microphone.Start(micDevice, true, clipLengthSec, sampleRate);
  48.  
  49.     if (micClip == null)
  50.     {
  51.         if (statusText)
  52.             statusText.text = "Не удалось включить микрофон";
  53.         yield break;
  54.     }
  55.  
  56.     float timeout = 2f;
  57.     while (Microphone.GetPosition(micDevice) <= 0 && timeout > 0f)
  58.     {
  59.         timeout -= Time.unscaledDeltaTime;
  60.         yield return null;
  61.     }
  62.  
  63.     if (timeout <= 0f)
  64.     {
  65.         if (statusText)
  66.             statusText.text = "Микрофон не запустился";
  67.         yield break;
  68.     }
  69.  
  70.     audioSource.loop = true;
  71.     audioSource.clip = micClip;
  72.     audioSource.mute = true;
  73.     audioSource.Play();
  74.  
  75.     micStarted = true;
  76.  
  77.     if (statusText)
  78.         statusText.text = "Микрофон включён";
  79.  
  80.     Debug.Log("Microphone started successfully");
  81. }
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment