UnityAudioOutput.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using DG.Tweening;
  3. using UnityEngine;
  4. using Object = UnityEngine.Object;
  5. namespace DevilLink2.Presentation
  6. {
  7. /// <summary>Fixed source pool with calibrated voice admission and explicit linear gain budgets.</summary>
  8. public sealed class UnityAudioOutput : IAudioOutput, ICalibratedAudioOutput
  9. {
  10. public const int EffectVoices = AudioVoicePolicy.Slots;
  11. private readonly GameObject root;
  12. private readonly AudioSource[] music = new AudioSource[2], effects = new AudioSource[EffectVoices];
  13. private readonly AudioCrossfade blend = new AudioCrossfade();
  14. private readonly AudioVoicePolicy voices = new AudioVoicePolicy();
  15. private readonly Func<double> clock;
  16. private readonly bool audible;
  17. private int active, generation;
  18. private float musicVolume = AudioMixCalibration.DefaultMusic, sfxVolume = AudioMixCalibration.DefaultSfx;
  19. private float voiceScale = 1, headroom = 1;
  20. private double lastMixTime = double.NaN;
  21. private Tween fade;
  22. public int ActiveEffectCount => voices.Count;
  23. public UnityAudioOutput(Transform owner, bool enablePlayback, Func<double> time = null)
  24. {
  25. audible = enablePlayback; clock = time ?? (() => Time.realtimeSinceStartupAsDouble);
  26. root = new GameObject("AudioChannels"); root.transform.SetParent(owner, false);
  27. for (int i = 0; i < music.Length; i++) music[i] = Source("BGM" + i, true);
  28. for (int i = 0; i < effects.Length; i++) effects[i] = Source("SFX" + i, false);
  29. }
  30. private AudioSource Source(string name, bool loop)
  31. {
  32. var go = new GameObject(name); go.transform.SetParent(root.transform, false);
  33. var source = go.AddComponent<AudioSource>(); source.playOnAwake = false; source.loop = loop; source.spatialBlend = 0;
  34. source.volume = 0; return source;
  35. }
  36. public void SwitchMusic(AudioClip clip)
  37. {
  38. int token = ++generation; fade?.Kill(false); fade = null;
  39. int next = 1 - active; active = next;
  40. var source = music[next]; source.Stop(); source.clip = clip;
  41. blend.Begin(next, clip != null); ApplyMix();
  42. if (audible && clip) source.Play();
  43. if (!audible) { blend.Advance(1); ApplyMix(); return; }
  44. float progress = 0;
  45. fade = DOTween.To(() => progress, t => {
  46. if (token != generation) return;
  47. progress = t; blend.Advance(t); ApplyMix();
  48. }, 1, .6f).SetUpdate(true).SetEase(Ease.Linear).SetRecyclable(false).OnComplete(() => {
  49. if (token != generation) return;
  50. music[1 - next].Stop(); if (!clip) source.Stop();
  51. });
  52. }
  53. private void ApplyMix(bool immediate = false)
  54. {
  55. double now = clock();
  56. float delta = double.IsNaN(lastMixTime) ? 0 : (float)Math.Max(0, now - lastMixTime);
  57. lastMixTime = now; voices.Expire(now);
  58. float targetVoiceScale = AudioMixCalibration.VoiceScale(voices.GainSum);
  59. voiceScale = immediate ? targetVoiceScale : AudioMixCalibration.Recover(voiceScale, targetVoiceScale, delta);
  60. float musicGain = musicVolume * (blend.First + blend.Second);
  61. float sfxGain = sfxVolume * voices.GainSum * voiceScale;
  62. float targetHeadroom = AudioMixCalibration.Headroom(musicGain, sfxGain);
  63. headroom = immediate ? targetHeadroom : AudioMixCalibration.Recover(headroom, targetHeadroom, delta);
  64. if (music[0]) music[0].volume = musicVolume * blend.First * headroom;
  65. if (music[1]) music[1].volume = musicVolume * blend.Second * headroom;
  66. for (int i = 0; i < effects.Length; i++) if (effects[i])
  67. {
  68. float gain = voices.GainAt(i);
  69. effects[i].volume = sfxVolume * gain * voiceScale * headroom;
  70. if (gain == 0 && effects[i].clip) { effects[i].Stop(); effects[i].clip = null; }
  71. }
  72. }
  73. public void Tick() { ApplyMix(); }
  74. public void SetMusicVolume(float value) { musicVolume = Mathf.Clamp01(value); ApplyMix(true); }
  75. public void SetSfxVolume(float value) { sfxVolume = Mathf.Clamp01(value); ApplyMix(true); }
  76. public bool TryPlayEffect(AudioClip clip, AudioCue cue, float gain)
  77. {
  78. if (!clip || !voices.TryStart(cue, gain, clock(), clip.length, out int slot)) return false;
  79. var source = effects[slot]; source.Stop(); source.clip = clip;
  80. ApplyMix(); if (audible) source.Play(); return true;
  81. }
  82. public void PlayEffect(AudioClip clip)
  83. {
  84. if (!clip) return;
  85. var cue = Enum.TryParse(clip.name, out AudioCue parsed) ? parsed : AudioCue.Tile_Match;
  86. TryPlayEffect(clip, cue, AudioMixCalibration.Gain(cue));
  87. }
  88. public void StopEffects() { voices.Clear(); foreach (var source in effects) if (source) { source.Stop(); source.clip = null; } ApplyMix(); }
  89. public void StopAll()
  90. {
  91. ++generation; fade?.Kill(false); fade = null; blend.Clear();
  92. foreach (var source in music) if (source) source.Stop(); StopEffects();
  93. }
  94. public void Dispose()
  95. {
  96. StopAll(); if (!root) return; root.SetActive(false);
  97. if (Application.isPlaying) Object.Destroy(root); else Object.DestroyImmediate(root);
  98. }
  99. }
  100. }