using System; using UnityEngine; namespace UMP { [RequireComponent(typeof(AudioSource))] public abstract class AudioOutput : MonoBehaviour { public enum AudioChannels { Both, Left, Right }; [SerializeField] private AudioChannels _audioChannel; public AudioChannels AudioChannel { get { return _audioChannel; } set { _audioChannel = value; } } private int _id; public int Id { get { return _id; } } private AudioSource _audioSource; public AudioSource AudioSource { get { if (_audioSource == null) _audioSource = GetComponent(); return _audioSource; } } private float[] _data; internal float[] Data { get { return _data; } set { _data = value; if (_outputDataListener != null && _data != null) _outputDataListener(_data, _audioChannel); } } internal void Init() { _id = GetInstanceID(); } public void Play() { if (_audioSource == null) _audioSource = GetComponent(); _audioSource.Play(); } public void Pause() { if (_audioSource == null) _audioSource = GetComponent(); _audioSource.Pause(); } public void Stop() { if (_audioSource == null) _audioSource = GetComponent(); _audioSource.Stop(); } public void RemoveAllListeners() { if (_audioFilterReadListener != null) { foreach (Action eh in _audioFilterReadListener.GetInvocationList()) _audioFilterReadListener -= eh; } if (_outputDataListener != null) { foreach (Action eh in _outputDataListener.GetInvocationList()) _outputDataListener -= eh; } } private event Action _outputDataListener; public event Action OutputDataListener { add { _outputDataListener = (Action)Delegate.Combine(_outputDataListener, value); } remove { if (_outputDataListener != null) _outputDataListener = (Action)Delegate.Remove(_outputDataListener, value); } } private event Action _audioFilterReadListener; internal event Action AudioFilterReadListener { add { _audioFilterReadListener = (Action)Delegate.Combine(_audioFilterReadListener, value); } remove { if (_audioFilterReadListener != null) _audioFilterReadListener = (Action)Delegate.Remove(_audioFilterReadListener, value); } } /// Native Unity "AudioSource" callback private void OnAudioFilterRead(float[] data, int nbChannels) { if (_audioFilterReadListener != null) _audioFilterReadListener(Id, data, _audioChannel); } } }