using System; using Fort23.Core; using UnityEngine; namespace Core.Audio { public class AudioSourcePool: IDisposable { private AudioSource _audioSource; private TimerEntity _timerEntity; private AssetHandle _assetHandle; public bool IsPlay; public System.Action OnFinish; public string CurrPlayName { get { return _currPlayName; } } public string _currPlayName; public void Init(Transform root) { GameObject gameObject = new GameObject(); _audioSource = gameObject.AddComponent(); gameObject.transform.SetParent(root); } public void Play(string audioName, AssetHandle audioClip, bool isLoop,float volume, float speed = 1) { if (audioClip == null) { return; } if (_assetHandle != null) { _assetHandle.Release(); } IsPlay = true; _currPlayName = audioName; _assetHandle = audioClip; _audioSource.clip = _assetHandle.AssetObject(); _audioSource.loop = isLoop; _audioSource.pitch = speed; _audioSource.volume = volume; if (speed > 1) { _audioSource.outputAudioMixerGroup = AudioManager.Instance.AudioMixerGroup; _audioSource.outputAudioMixerGroup.audioMixer.SetFloat("path", 1f / speed); } else { _audioSource.outputAudioMixerGroup = null; } _audioSource.Play(); if (!isLoop) { _timerEntity = TimerComponent.Instance.AddTimer((long) (_audioSource.clip.length * 1000L), delegate { Finish(); }); } } public void Finish() { IsPlay = false; OnFinish?.Invoke(); _audioSource.Stop(); AudioManager.Instance.Recycle(this); TimerComponent.Instance.Remove(_timerEntity); _timerEntity = null; } public void Stop() { IsPlay = false; _audioSource.Stop(); } public void Pause() { _audioSource.Pause(); } public void UnPause() { _audioSource.UnPause(); } public void Dispose() { if (_assetHandle != null) { _assetHandle.Release(); } } } }