using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.Networking; using UnityEngine.Video; // 播放音樂並依 SongClock 生成音符 // 音樂用 PlayScheduled 排在 DSP 時鐘上,音符時間與音訊同一個時間基準,不會累積誤差 // 在 GridDisplay(過期判定)之後才生成新音符,掉幀時也不會先蓋掉同格未結算的音符 // // 兩種模式: // - menuSheet 有指定(主畫面):用內建的背景譜面,音樂由 AudioSource 的 Play On Awake 播放 // - menuSheet 留空(遊玩):載入 SongLibrary.Current 這個曲包的音樂、譜面與影片 [DefaultExecutionOrder(100)] public class MusicPlayer : MonoBehaviour { public AudioSource audioSource; public GridDisplaySpawner gridDisplaySpawner; [Tooltip("主畫面的內建背景譜面;留空時載入目前選擇的曲包")] public TextAsset menuSheet; // 音樂開始前的準備時間,讓開頭的音符也有完整的出現動畫 public float leadInSec = 1.0f; // 曲包影片的透明度(0 = 不顯示影片) [Range(0f, 1f)] public float videoAlpha = 0.4f; public SongInfo Song { get; private set; } public int Level { get; private set; } public bool Ready { get; private set; } public string Error { get; private set; } public int TotalNotes => events.Count; public int SkippedNotes { get; private set; } private readonly List events = new List(); private int nextEvent = 0; private AudioClip loadedClip; private VideoPlayer video; private bool videoStarted; // 歌曲(含結尾緩衝)是否已結束 public bool Finished => Ready && SongClock.Running && audioSource.clip != null && SongClock.Now > audioSource.clip.length + NoteJudge.BadWindow + 0.5; void Start() { if (menuSheet != null) StartMenu(); else StartCoroutine(LoadAndPlaySong()); } void OnDestroy() { SongClock.Stop(); if (audioSource != null) audioSource.Stop(); if (loadedClip != null) { if (audioSource != null) audioSource.clip = null; Destroy(loadedClip); } } // 主畫面:音樂已由 Play On Awake 開始播放,時鐘對齊目前播放位置 void StartMenu() { try { SetEvents(ChartLoader.Parse(menuSheet.text, 0, out int skipped)); SkippedNotes = skipped; } catch (Exception e) { Debug.LogError("[MusicPlayer] 主畫面譜面讀取失敗:" + e.Message); } double dspStart; if (audioSource.isPlaying) { dspStart = AudioSettings.dspTime - audioSource.time; } else { dspStart = AudioSettings.dspTime + leadInSec; audioSource.PlayScheduled(dspStart); } SongClock.Begin(dspStart); Ready = true; } IEnumerator LoadAndPlaySong() { Song = SongLibrary.Current; Level = PlayerPrefs.GetInt("NowPlayingLevel", 1); if (Song == null) { Fail("沒有選擇曲目"); yield break; } if (!Song.HasLevel(Level)) Level = Song.FirstLevel(); if (Level == 0) { Fail("這個曲包沒有譜面"); yield break; } try { SetEvents(ChartLoader.LoadFile(Song.ChartPath(Level), Song.offsetMs, out int skipped)); SkippedNotes = skipped; } catch (Exception e) { Fail("譜面讀取失敗:" + e.Message); yield break; } string musicPath = Song.MusicPath; if (musicPath == null) { Fail("曲包沒有音樂"); yield break; } using (var www = LoadAudio(musicPath)) { yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Fail("音樂載入失敗:" + www.error); yield break; } loadedClip = DownloadHandlerAudioClip.GetContent(www); } if (loadedClip == null || loadedClip.length <= 0f) { Fail("音樂無法解碼"); yield break; } audioSource.clip = loadedClip; if (videoAlpha > 0f && Song.VideoPath != null) SetupVideo(Song.VideoPath); double start = AudioSettings.dspTime + leadInSec; audioSource.PlayScheduled(start); SongClock.Begin(start); Ready = true; Debug.Log($"[MusicPlayer] {Song.id} {SongInfo.LevelName(Level)}: {events.Count} events, skipped {SkippedNotes}, clip {loadedClip.length:0.0}s"); } void Fail(string message) { Error = message; Debug.LogError("[MusicPlayer] " + message); } void SetEvents(List list) { events.Clear(); events.AddRange(list); nextEvent = 0; } // 本機檔案 → UnityWebRequest 用的 file:// 網址(處理空白與 Windows 路徑) public static string FileUrl(string path) => new Uri(Path.GetFullPath(path)).AbsoluteUri; // 載入曲包音樂:ogg / mp3 保持壓縮(整首不解壓,省記憶體); // wav 本來就是 PCM,開壓縮模式在 Android 上會讓主執行緒卡死,所以直接載入 public static UnityWebRequest LoadAudio(string path) { AudioType type = AudioTypeOf(path); var www = UnityWebRequestMultimedia.GetAudioClip(FileUrl(path), type); ((DownloadHandlerAudioClip)www.downloadHandler).compressed = type != AudioType.WAV; return www; } public static AudioType AudioTypeOf(string path) { switch (Path.GetExtension(path).ToLowerInvariant()) { case ".ogg": return AudioType.OGGVORBIS; case ".mp3": return AudioType.MPEG; default: return AudioType.WAV; } } // 曲包的 video.mp4:畫在攝影機最後方當背景,聲音一律用 music 檔 void SetupVideo(string path) { Camera cam = Camera.main; if (cam == null) return; var go = new GameObject("PackVideo"); video = go.AddComponent(); video.playOnAwake = false; video.source = VideoSource.Url; video.url = path; video.renderMode = VideoRenderMode.CameraFarPlane; video.targetCamera = cam; video.targetCameraAlpha = videoAlpha; video.aspectRatio = VideoAspectRatio.FitOutside; video.audioOutputMode = VideoAudioOutputMode.None; video.isLooping = false; video.skipOnDrop = true; video.Prepare(); } void Update() { if (!Ready || !SongClock.Running) return; double now = SongClock.Now; if (video != null && !videoStarted && now >= 0 && video.isPrepared) { if (now > 0.05) video.time = now; // 準備得比音樂慢:從目前位置接上 video.Play(); videoStarted = true; } double spawnUntil = now + GridDisplay.AppearLead; while (nextEvent < events.Count && events[nextEvent].hitTime <= spawnUntil) { var e = events[nextEvent++]; switch (e.type) { case "tap": gridDisplaySpawner.PlayNoteTap(e.x, e.y, e.hitTime); break; case "hold": gridDisplaySpawner.PlayNoteHold(e.x, e.y, e.holdMs, e.hitTime); break; case "slide": gridDisplaySpawner.PlayNoteSlide(e.x, e.y, e.hitTime); break; } } } }