Hasli4

Untitled

Mar 25th, 2026
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.44 KB | None | 0 0
  1. using UnityEngine;
  2. using TMPro;
  3. using UnityEngine.UI;
  4. using System.Collections;
  5.  
  6. #if UNITY_ANDROID
  7. using UnityEngine.Android;
  8. #endif
  9.  
  10. [RequireComponent(typeof(AudioSource))]
  11. public class TunerController : MonoBehaviour
  12. {
  13. [Header("UI")]
  14. public TextMeshProUGUI freqText;
  15. public TextMeshProUGUI noteText;
  16. public TextMeshProUGUI centsText;
  17. public Image tuningNeedle;
  18. public TextMeshProUGUI statusText; // можно оставить пустым, если не нужен
  19.  
  20. [Header("Microphone settings")]
  21. public int sampleRate = 16000;
  22. public int clipLengthSec = 1;
  23. public string microphoneDevice = "";
  24.  
  25. [Header("Detection settings")]
  26. public float minFreq = 80f;
  27. public float maxFreq = 1200f;
  28. public float rmsThreshold = 0.0015f;
  29. public float acfPeakThreshold = 0.25f;
  30. public int sampleWindow = 4096;
  31.  
  32. AudioSource audioSource;
  33. AudioClip micClip;
  34. string micDevice;
  35. float uiInterval = 0.09f;
  36. float uiTimer = 0f;
  37.  
  38. bool micStarted = false;
  39. bool permissionRequested = false;
  40.  
  41. void Start()
  42. {
  43. audioSource = GetComponent<AudioSource>();
  44.  
  45. if (statusText)
  46. statusText.text = "Проверяю доступ к микрофону...";
  47.  
  48. TryStartMicrophone();
  49. }
  50.  
  51. void OnApplicationFocus(bool hasFocus)
  52. {
  53. if (hasFocus && !micStarted)
  54. {
  55. TryStartMicrophone();
  56. }
  57. }
  58.  
  59. void TryStartMicrophone()
  60. {
  61. #if UNITY_ANDROID
  62. if (Permission.HasUserAuthorizedPermission(Permission.Microphone))
  63. {
  64. StartCoroutine(StartMicRoutine());
  65. return;
  66. }
  67.  
  68. if (permissionRequested)
  69. return;
  70.  
  71. permissionRequested = true;
  72.  
  73. var callbacks = new PermissionCallbacks();
  74. callbacks.PermissionGranted += OnPermissionGranted;
  75. callbacks.PermissionDenied += OnPermissionDenied;
  76. callbacks.PermissionDeniedAndDontAskAgain += OnPermissionDeniedDontAskAgain;
  77.  
  78. Permission.RequestUserPermission(Permission.Microphone, callbacks);
  79. #else
  80. StartCoroutine(StartMicRoutine());
  81. #endif
  82. }
  83.  
  84. #if UNITY_ANDROID
  85. void OnPermissionGranted(string permissionName)
  86. {
  87. StartCoroutine(StartMicRoutine());
  88. }
  89.  
  90. void OnPermissionDenied(string permissionName)
  91. {
  92. if (statusText)
  93. statusText.text = "Нужен доступ к микрофону";
  94. }
  95.  
  96. void OnPermissionDeniedDontAskAgain(string permissionName)
  97. {
  98. if (statusText)
  99. statusText.text = "Разреши микрофон в настройках";
  100. }
  101. #endif
  102.  
  103. IEnumerator StartMicRoutine()
  104. {
  105. if (micStarted)
  106. yield break;
  107.  
  108. if (Microphone.devices.Length == 0)
  109. {
  110. if (statusText)
  111. statusText.text = "Микрофон не найден";
  112. yield break;
  113. }
  114.  
  115. micDevice = string.IsNullOrEmpty(microphoneDevice) ? Microphone.devices[0] : microphoneDevice;
  116.  
  117. // даём системе 1 кадр после окна разрешения
  118. yield return null;
  119.  
  120. micClip = Microphone.Start(micDevice, true, clipLengthSec, sampleRate);
  121.  
  122. if (micClip == null)
  123. {
  124. if (statusText)
  125. statusText.text = "Не удалось включить микрофон";
  126. yield break;
  127. }
  128.  
  129. // ждём, пока микрофон реально начнёт писать, но без вечного зависания
  130. float timeout = 2f;
  131. while (Microphone.GetPosition(micDevice) <= 0 && timeout > 0f)
  132. {
  133. timeout -= Time.unscaledDeltaTime;
  134. yield return null;
  135. }
  136.  
  137. if (timeout <= 0f)
  138. {
  139. if (statusText)
  140. statusText.text = "Микрофон не запустился";
  141. yield break;
  142. }
  143.  
  144. audioSource.loop = true;
  145. audioSource.clip = micClip;
  146. audioSource.mute = true;
  147. audioSource.Play();
  148.  
  149. micStarted = true;
  150.  
  151. if (statusText)
  152. statusText.text = "Микрофон включён";
  153. }
  154.  
  155. void Update()
  156. {
  157. if (!micStarted || micClip == null)
  158. return;
  159.  
  160. uiTimer += Time.unscaledDeltaTime;
  161. if (uiTimer < uiInterval) return;
  162. uiTimer = 0f;
  163.  
  164. float freq = DetectPitch();
  165. if (freq > 0)
  166. {
  167. float midiFloat = FrequencyToMidi(freq);
  168. int octave;
  169. string note = MidiToNoteName(midiFloat, out octave);
  170. float cents = FrequencyToCents(freq, midiFloat);
  171.  
  172. if (freqText) freqText.SetText("{0:F1} Hz", freq);
  173. if (noteText) noteText.text = $"{note}{octave}";
  174. if (centsText) centsText.SetText("{0:+0.0;-0.0}¢", cents);
  175.  
  176. if (tuningNeedle)
  177. {
  178. float angle = Mathf.Clamp(cents, -50f, 50f) / 50f * 45f;
  179. tuningNeedle.rectTransform.localRotation = Quaternion.Euler(0, 0, -angle);
  180. }
  181. }
  182. else
  183. {
  184. if (freqText) freqText.SetText("-- Hz");
  185. if (noteText) noteText.SetText("-");
  186. if (centsText) centsText.SetText("");
  187. if (tuningNeedle) tuningNeedle.rectTransform.localRotation = Quaternion.Euler(0, 0, 0);
  188. }
  189. }
  190.  
  191. void OnDestroy()
  192. {
  193. if (!string.IsNullOrEmpty(micDevice) && Microphone.IsRecording(micDevice))
  194. Microphone.End(micDevice);
  195. }
  196.  
  197. float DetectPitch()
  198. {
  199. if (micClip == null) return -1f;
  200.  
  201. int micPos = Microphone.GetPosition(micDevice);
  202. if (micPos <= 0) return -1f;
  203.  
  204. float[] samples = new float[sampleWindow];
  205. int startPos = micPos - sampleWindow;
  206.  
  207. if (startPos >= 0)
  208. {
  209. micClip.GetData(samples, startPos);
  210. }
  211. else
  212. {
  213. int part1 = sampleWindow + startPos;
  214. float[] tail = new float[part1];
  215. float[] head = new float[sampleWindow - part1];
  216.  
  217. micClip.GetData(tail, micClip.samples - part1);
  218. micClip.GetData(head, 0);
  219.  
  220. System.Array.Copy(tail, 0, samples, 0, part1);
  221. System.Array.Copy(head, 0, samples, part1, head.Length);
  222. }
  223.  
  224. float mean = 0f;
  225. for (int i = 0; i < samples.Length; i++) mean += samples[i];
  226. mean /= samples.Length;
  227.  
  228. for (int i = 0; i < samples.Length; i++) samples[i] -= mean;
  229.  
  230. float sumSq = 0f;
  231. for (int i = 0; i < samples.Length; i++) sumSq += samples[i] * samples[i];
  232.  
  233. float rms = Mathf.Sqrt(sumSq / samples.Length);
  234. if (rms < rmsThreshold)
  235. return -1f;
  236.  
  237. ApplyHammingWindow(samples);
  238.  
  239. int maxLag = Mathf.FloorToInt(sampleRate / minFreq);
  240. int minLag = Mathf.CeilToInt(sampleRate / maxFreq);
  241.  
  242. if (maxLag >= samples.Length) maxLag = samples.Length - 1;
  243. if (minLag < 1) minLag = 1;
  244.  
  245. float acf0 = 0f;
  246. for (int i = 0; i < samples.Length; i++) acf0 += samples[i] * samples[i];
  247. if (acf0 <= 1e-9f) return -1f;
  248.  
  249. float[] acf = new float[maxLag + 1];
  250.  
  251. for (int lag = minLag; lag <= maxLag; lag++)
  252. {
  253. float sum = 0f;
  254. for (int i = 0; i < samples.Length - lag; i++)
  255. sum += samples[i] * samples[i + lag];
  256.  
  257. acf[lag] = sum / acf0;
  258. }
  259.  
  260. int bestLag = -1;
  261. float bestVal = 0f;
  262.  
  263. for (int lag = minLag; lag <= maxLag; lag++)
  264. {
  265. if (acf[lag] > bestVal)
  266. {
  267. bestVal = acf[lag];
  268. bestLag = lag;
  269. }
  270. }
  271.  
  272. if (bestLag <= 0) return -1f;
  273. if (bestVal < acfPeakThreshold) return -1f;
  274.  
  275. float refinedLag = ParabolicInterpolation(acf, bestLag);
  276. float frequency = sampleRate / refinedLag;
  277.  
  278. return frequency;
  279. }
  280.  
  281. static void ApplyHammingWindow(float[] data)
  282. {
  283. int N = data.Length;
  284. for (int i = 0; i < N; i++)
  285. {
  286. float w = 0.54f - 0.46f * Mathf.Cos(2f * Mathf.PI * i / (N - 1));
  287. data[i] *= w;
  288. }
  289. }
  290.  
  291. static float ParabolicInterpolation(float[] acf, int lag)
  292. {
  293. if (lag <= 0 || lag >= acf.Length - 1) return lag;
  294.  
  295. float y0 = acf[lag - 1];
  296. float y1 = acf[lag];
  297. float y2 = acf[lag + 1];
  298. float denom = (y0 - 2f * y1 + y2);
  299.  
  300. if (Mathf.Abs(denom) < 1e-8f) return lag;
  301.  
  302. float shift = 0.5f * (y0 - y2) / denom;
  303. return lag + shift;
  304. }
  305.  
  306. static float FrequencyToMidi(float freq)
  307. {
  308. return 69f + 12f * Mathf.Log(freq / 440f, 2f);
  309. }
  310.  
  311. static string MidiToNoteName(float midiFloat, out int octave)
  312. {
  313. int midi = Mathf.RoundToInt(midiFloat);
  314. string[] names = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  315. int noteIndex = midi % 12;
  316. octave = (midi / 12) - 1;
  317. return names[(noteIndex + 12) % 12];
  318. }
  319.  
  320. static float FrequencyToCents(float freq, float midiFloat)
  321. {
  322. float nearestMidi = Mathf.Round(midiFloat);
  323. return 1200f * Mathf.Log(freq / MidiToFrequency(nearestMidi), 2f);
  324. }
  325.  
  326. static float MidiToFrequency(float midi)
  327. {
  328. return 440f * Mathf.Pow(2f, (midi - 69f) / 12f);
  329. }
  330. }
Advertisement
Add Comment
Please, Sign In to add comment