ThreeKingdomsSlingshot/Assets/Scripts/Runtime/Audio/SoundPlayer.cs

160 lines
5.4 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace TKS
{
/// <summary>재생 장치(씬이 바뀌어도 남음) · AudioListener 가 없으면 스스로 켬 · 모든 Button 누름 = ui_click 공통 중계.</summary>
public class SoundPlayer : MonoBehaviour
{
const int Voices = 16;
const float BgmFade = 0.8f, DuckLevel = 0.25f;
readonly List<AudioSource> sfx = new List<AudioSource>();
readonly AudioSource[] bgm = new AudioSource[2];
readonly float[] bgmBase = new float[2];
int bgmActive;
float fadeT = 1f, duckUntil, listenerCheck;
AudioListener listener;
string pendingClick;
readonly List<RaycastResult> hits = new List<RaycastResult>();
public string BgmKey { get; private set; }
public static SoundPlayer Create()
{
var go = new GameObject("Sound");
DontDestroyOnLoad(go);
var p = go.AddComponent<SoundPlayer>();
p.Init();
return p;
}
void Init()
{
for (int i = 0; i < Voices; i++) sfx.Add(NewSource(false));
for (int i = 0; i < 2; i++) bgm[i] = NewSource(true);
CheckListener();
}
AudioSource NewSource(bool loop)
{
var s = gameObject.AddComponent<AudioSource>();
s.playOnAwake = false;
s.loop = loop;
s.spatialBlend = 0f;
return s;
}
public void PlaySfx(AudioClip clip, float vol, float pitch, float duck)
{
AudioSource src = null;
foreach (var s in sfx)
if (!s.isPlaying)
{
src = s;
break;
}
if (src == null)
{
src = sfx[0];
sfx.RemoveAt(0);
sfx.Add(src);
}
src.Stop();
src.clip = clip;
src.pitch = pitch;
src.volume = Sound.Mute ? 0f : vol * Sound.SfxVolume;
src.Play();
if (duck > 0f) duckUntil = Mathf.Max(duckUntil, Time.unscaledTime + duck / Mathf.Max(0.1f, pitch));
}
public void PlayBgm(string key, AudioClip clip, float vol)
{
BgmKey = key;
bgmActive = 1 - bgmActive;
var s = bgm[bgmActive];
bgmBase[bgmActive] = clip != null ? vol : 0f;
if (clip != null)
{
s.clip = clip;
s.volume = 0f;
s.Play();
}
fadeT = 0f;
}
void Update()
{
listenerCheck -= Time.unscaledDeltaTime;
if (listenerCheck <= 0f)
{
listenerCheck = 0.5f;
CheckListener();
}
UpdateBgm();
UiRelay();
}
void LateUpdate()
{
if (pendingClick == null) return;
string k = pendingClick;
pendingClick = null;
if (!Sound.UiPlayedThisFrame) Sound.PlayUi(k);
}
void UpdateBgm()
{
fadeT = Mathf.Min(1f, fadeT + Time.unscaledDeltaTime / BgmFade);
float duck = Time.unscaledTime < duckUntil ? DuckLevel : 1f;
float master = Sound.Mute ? 0f : Sound.BgmVolume * duck;
for (int i = 0; i < 2; i++)
{
var s = bgm[i];
if (s == null) continue;
float k = i == bgmActive ? fadeT : 1f - fadeT;
s.volume = bgmBase[i] * k * master;
if (i != bgmActive && fadeT >= 1f && s.isPlaying) s.Stop();
}
}
void CheckListener()
{
var all = FindObjectsByType<AudioListener>(FindObjectsSortMode.None);
int others = 0;
foreach (var l in all)
if (l != listener && l.enabled && l.gameObject.activeInHierarchy) others++;
if (others == 0)
{
if (listener == null) listener = gameObject.AddComponent<AudioListener>();
listener.enabled = true;
}
else if (listener != null) listener.enabled = false;
}
/// <summary>모든 Button 누름 = 한 곳에서(버튼마다 코드 없음): 놓는 순간 그 자리의 Button → SoundTag 소리 · 없으면 ui_click · 누를 수 없는 버튼 = ui_error.
/// 같은 프레임에 버튼 동작이 다른 UI 소리(화면 · 팝업 · 닫기 · 탭)를 냈으면 그 소리만(LateUpdate 에서 판단).</summary>
void UiRelay()
{
if (!Input.GetMouseButtonUp(0)) return;
var es = EventSystem.current;
if (es == null) return;
var ped = new PointerEventData(es) { position = Input.mousePosition };
hits.Clear();
es.RaycastAll(ped, hits);
if (hits.Count == 0 || hits[0].gameObject == null) return;
var b = hits[0].gameObject.GetComponentInParent<Button>();
if (b == null) return;
var tag = b.GetComponent<SoundTag>();
if (tag != null)
{
if (!string.IsNullOrEmpty(tag.key)) pendingClick = tag.key;
return;
}
pendingClick = b.IsInteractable() ? SoundKeys.UiClick : SoundKeys.UiError;
}
}
}