using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem.EnhancedTouch; using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch; using UnityEngine.SceneManagement; using UnityEngine.UI; // 設定頁:音訊延遲校正 // 播放節拍聲,玩家只聽聲音跟著點擊;取偏差中位數存成 AudioOffsetMs public class CalibrationController : MonoBehaviour { private const string SceneName = "SettingScene"; private const double Bpm = 100; private const int BeatCount = 16; private const int WarmupBeats = 4; private const double LeadIn = 1.0; private double Interval => 60.0 / Bpm; private Font font; private Text offsetText; private Text statusText; private Text beatText; private Button startButton; private AudioSource audioSource; private AudioClip clickTrack; private bool running; private readonly List deltas = new List(); private readonly HashSet ignoredTouches = new HashSet(); // 進入設定頁時自動加入(不需改動場景) [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] static void Register() { SceneManager.sceneLoaded += (scene, mode) => { if (scene.name == SceneName) new GameObject("CalibrationController").AddComponent(); }; } void Start() { // 沿用場景字型,並隱藏原本的佔位文字 foreach (var t in FindObjectsByType(FindObjectsSortMode.None)) { if (font == null) font = t.font; if (t.text.Trim() == "Empty") t.gameObject.SetActive(false); } EnhancedTouchSupport.Enable(); audioSource = gameObject.AddComponent(); clickTrack = BuildClickTrack(); BuildUI(); RefreshOffset(); } void OnDestroy() { if (running) SongClock.Stop(); } void Update() { if (!running) return; double now = SongClock.Now; int beat = (int)System.Math.Floor((now - LeadIn) / Interval) + 1; beatText.text = beat <= 0 ? "準備…" : $"{Mathf.Min(beat, BeatCount)} / {BeatCount}"; PollTaps(now); if (now > LeadIn + (BeatCount - 0.5) * Interval + 0.3) Finish(); } void PollTaps(double now) { double real = Time.realtimeSinceStartupAsDouble; foreach (var t in Touch.activeTouches) { if (t.phase != UnityEngine.InputSystem.TouchPhase.Began) continue; if (ignoredTouches.Contains(t.touchId)) continue; double age = System.Math.Min(0.1, System.Math.Max(0, real - t.startTime)); if (CalibrationMath.TryBeatDelta(now - age, LeadIn, Interval, BeatCount, WarmupBeats, out double d)) deltas.Add(d); } } void StartCalibration() { deltas.Clear(); ignoredTouches.Clear(); // 開始前已按著的手指(按下「開始」的那一下)不計入 foreach (var t in Touch.activeTouches) ignoredTouches.Add(t.touchId); double dspStart = AudioSettings.dspTime + 0.2; audioSource.clip = clickTrack; audioSource.PlayScheduled(dspStart); SongClock.Begin(dspStart, applyOffset: false); running = true; startButton.interactable = false; statusText.text = "閉上眼睛,跟著聲音點擊螢幕任意處"; } void Finish() { running = false; SongClock.Stop(); audioSource.Stop(); startButton.interactable = true; beatText.text = ""; int needed = (BeatCount - WarmupBeats) / 2; if (deltas.Count < needed) { statusText.text = $"有效點擊太少({deltas.Count} 次),請再試一次"; return; } int ms = (int)System.Math.Round(CalibrationMath.Median(deltas) * 1000); SetOffset(ms); statusText.text = $"已套用:{deltas.Count} 次有效點擊,中位數 {ms:+0;-0;0} ms"; } void SetOffset(int ms) { PlayerPrefs.SetInt(SongClock.OffsetPrefKey, Mathf.Clamp(ms, -500, 500)); PlayerPrefs.Save(); RefreshOffset(); } void RefreshOffset() { int ms = PlayerPrefs.GetInt(SongClock.OffsetPrefKey, 0); offsetText.text = $"目前延遲補償:{ms:+0;-0;0} ms"; } // 產生整段節拍聲(每四拍第一拍較高音) AudioClip BuildClickTrack() { int rate = AudioSettings.outputSampleRate; double length = LeadIn + BeatCount * Interval + 0.5; var data = new float[(int)(rate * length)]; int clickLen = (int)(rate * 0.04); for (int b = 0; b < BeatCount; b++) { int start = (int)((LeadIn + b * Interval) * rate); double freq = b % 4 == 0 ? 1760 : 1320; for (int i = 0; i < clickLen && start + i < data.Length; i++) { double env = System.Math.Exp(-i / (rate * 0.008)); data[start + i] = (float)(System.Math.Sin(2 * System.Math.PI * freq * i / rate) * env * 0.8); } } var clip = AudioClip.Create("CalibrationClicks", data.Length, 1, rate, false); clip.SetData(data, 0); return clip; } // ---------- UI ---------- void BuildUI() { Canvas canvas = FindAnyObjectByType(); Transform parent = canvas.transform; AddText(parent, "延遲校正", 72, Color.white, 520); AddText(parent, "戴上平常玩的耳機,按「開始」後\n只聽聲音、跟著節拍點擊螢幕\n前 4 拍為暖身不計分", 40, new Color(0.8f, 0.8f, 0.8f), 340); offsetText = AddText(parent, "", 52, new Color(1f, 0.42f, 0.8f), 160); beatText = AddText(parent, "", 96, Color.white, 0); statusText = AddText(parent, "", 38, new Color(0.8f, 0.8f, 0.8f), -140); startButton = AddButton(parent, "開始", new Vector2(0, -300), new Vector2(420, 120), StartCalibration); AddButton(parent, "-5 ms", new Vector2(-300, -460), new Vector2(240, 100), () => SetOffset(PlayerPrefs.GetInt(SongClock.OffsetPrefKey, 0) - 5)); AddButton(parent, "重設", new Vector2(0, -460), new Vector2(240, 100), () => SetOffset(0)); AddButton(parent, "+5 ms", new Vector2(300, -460), new Vector2(240, 100), () => SetOffset(PlayerPrefs.GetInt(SongClock.OffsetPrefKey, 0) + 5)); AddText(parent, "正值 = 聲音比畫面晚(藍牙耳機通常為正)", 32, new Color(0.55f, 0.55f, 0.55f), -580); AddText(parent, $"匯入曲包:用檔案管理員或瀏覽器開啟 .zip → 選擇 Rhyculator\n目前已匯入 {SongLibrary.Songs.Count} 首", 30, new Color(0.55f, 0.55f, 0.55f), -760); } Text AddText(Transform parent, string content, int size, Color color, float y) { var go = new GameObject("CalibText", typeof(RectTransform)); go.transform.SetParent(parent, false); var text = go.AddComponent(); text.font = font; text.text = content; text.fontSize = size; text.color = color; text.alignment = TextAnchor.MiddleCenter; text.horizontalOverflow = HorizontalWrapMode.Overflow; text.verticalOverflow = VerticalWrapMode.Overflow; text.raycastTarget = false; var rt = text.rectTransform; rt.anchorMin = rt.anchorMax = new Vector2(0.5f, 0.5f); rt.sizeDelta = new Vector2(1000, size * 1.5f); rt.anchoredPosition = new Vector2(0, y); return text; } Button AddButton(Transform parent, string label, Vector2 pos, Vector2 size, UnityEngine.Events.UnityAction onClick) { var go = new GameObject("CalibButton", typeof(RectTransform)); go.transform.SetParent(parent, false); var img = go.AddComponent(); img.color = new Color(0.33f, 0.33f, 0.33f); var btn = go.AddComponent