|
| 1 | +#nullable enable |
| 2 | +using UnityEngine; |
| 3 | +using UnityEngine.Audio; |
| 4 | + |
| 5 | +namespace ProjectVG.Core.Audio |
| 6 | +{ |
| 7 | + public class AudioControllerCore : MonoBehaviour |
| 8 | + { |
| 9 | + [SerializeField] protected AudioSource _audioSource; |
| 10 | + [SerializeField] protected AudioMixerGroup _audioMixerGroup; |
| 11 | + |
| 12 | + protected float _volume = 1f; |
| 13 | + protected string _volumeParameterName = ""; |
| 14 | + |
| 15 | + public virtual void Initialize(string volumeParameterName) |
| 16 | + { |
| 17 | + _volumeParameterName = volumeParameterName; |
| 18 | + |
| 19 | + // AudioSource가 없으면 자동 생성 |
| 20 | + if (_audioSource == null) |
| 21 | + { |
| 22 | + _audioSource = gameObject.AddComponent<AudioSource>(); |
| 23 | + _audioSource.playOnAwake = false; |
| 24 | + _audioSource.loop = false; |
| 25 | + _audioSource.volume = _volume; |
| 26 | + } |
| 27 | + |
| 28 | + // AudioMixerGroup이 설정되지 않은 경우 AudioManager에서 자동 할당 |
| 29 | + if (_audioMixerGroup == null) |
| 30 | + { |
| 31 | + _audioMixerGroup = GetAudioMixerGroupFromManager(); |
| 32 | + } |
| 33 | + |
| 34 | + if (_audioSource != null && _audioMixerGroup != null) |
| 35 | + { |
| 36 | + _audioSource.outputAudioMixerGroup = _audioMixerGroup; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + protected virtual AudioMixerGroup? GetAudioMixerGroupFromManager() |
| 41 | + { |
| 42 | + // 하위 클래스에서 오버라이드하여 적절한 그룹 반환 |
| 43 | + return null; |
| 44 | + } |
| 45 | + |
| 46 | + public virtual void SetVolume(float volume) |
| 47 | + { |
| 48 | + _volume = Mathf.Clamp01(volume); |
| 49 | + |
| 50 | + if (_audioMixerGroup != null && !string.IsNullOrEmpty(_volumeParameterName)) |
| 51 | + { |
| 52 | + float dbValue = _volume > 0 ? 20f * Mathf.Log10(_volume) : -80f; |
| 53 | + _audioMixerGroup.audioMixer.SetFloat(_volumeParameterName, dbValue); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public virtual void Stop() |
| 58 | + { |
| 59 | + if (_audioSource != null) |
| 60 | + { |
| 61 | + _audioSource.Stop(); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + public virtual bool IsPlaying() |
| 66 | + { |
| 67 | + return _audioSource != null && _audioSource.isPlaying; |
| 68 | + } |
| 69 | + |
| 70 | + public virtual float GetVolume() |
| 71 | + { |
| 72 | + return _volume; |
| 73 | + } |
| 74 | + |
| 75 | + public AudioSource GetAudioSource() => _audioSource; |
| 76 | + public AudioMixerGroup GetAudioMixerGroup() => _audioMixerGroup; |
| 77 | + } |
| 78 | +} |
0 commit comments