using System; using System.Collections; using System.Collections.Generic; using SpellBoundAR.MusicalInstruments.Piano; using SpellBoundAR.MusicalInstruments.SheetMusic; using UnityEngine; namespace SpellBoundAR.MusicalInstruments.Autoplay { public class Autoplayer : MonoBehaviour { public static event Action OnAnyPlayingChanged; private static readonly Dictionary Multipliers = new () { { WrittenNoteTimeValue.Whole, 1f }, { WrittenNoteTimeValue.Half, .5f }, { WrittenNoteTimeValue.Quarter, .25f }, { WrittenNoteTimeValue.Eighth, .125f }, { WrittenNoteTimeValue.Sixteenth, .0625f }, }; [Header("Settings")] [SerializeField] private float secondsPerMeasure = 1f; [Header("References")] [SerializeField] private List keys; [Header("Cache")] private bool _isPlaying; private readonly Dictionary _keysDictionary = new (); public float SecondsPerMeasure { get => secondsPerMeasure; set => secondsPerMeasure = value; } public bool IsPlaying { get => _isPlaying; private set { if (_isPlaying == value) return; _isPlaying = value; OnAnyPlayingChanged?.Invoke(this); } } private void Awake() => BuildKeysDictionary(); private void BuildKeysDictionary() { _keysDictionary.Clear(); foreach (PianoKey key in keys) { if (key != null && key.Tone != null && !_keysDictionary.ContainsKey(key.Tone)) { _keysDictionary.Add(key.Tone, key); } } } private void OnEnable() => Stop(); private void OnDisable() => Stop(); public void Play() { Stop(); StartCoroutine(PlaybackCoroutine()); } private IEnumerator PlaybackCoroutine() { if (!MusicalInstrumentsManager.Song) yield break; IsPlaying = true; foreach(Measure measure in MusicalInstrumentsManager.Song.Measures) { if (measure == null) continue; foreach (WrittenNote writtenNote in measure.WrittenNotes) { if (writtenNote == null) continue; Tone tone = writtenNote.Note ? writtenNote.Note.Tone : null; if (tone && _keysDictionary.ContainsKey(tone)) _keysDictionary[tone].PlayNote(PlayerType.Computer); float delay = secondsPerMeasure * Multipliers[writtenNote.TimeValue]; if (writtenNote.Dotted) delay += delay / 2f; yield return new WaitForSecondsRealtime(delay); if (tone && _keysDictionary.ContainsKey(tone)) _keysDictionary[tone].StopNote(); } } StopAllNotes(); IsPlaying = false; } public void Stop() { StopAllCoroutines(); StopAllNotes(); IsPlaying = false; } private void StopAllNotes() { foreach (PianoKey key in keys) if (key) key.StopNote(); } } }