AudioSourcePool.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using Fort23.Core;
  3. using UnityEngine;
  4. namespace Core.Audio
  5. {
  6. public class AudioSourcePool: IDisposable
  7. {
  8. private AudioSource _audioSource;
  9. private TimerEntity _timerEntity;
  10. private AssetHandle _assetHandle;
  11. public bool IsPlay;
  12. public System.Action OnFinish;
  13. public string CurrPlayName
  14. {
  15. get { return _currPlayName; }
  16. }
  17. public string _currPlayName;
  18. public void Init(Transform root)
  19. {
  20. GameObject gameObject = new GameObject();
  21. _audioSource = gameObject.AddComponent<AudioSource>();
  22. gameObject.transform.SetParent(root);
  23. }
  24. public void Play(string audioName, AssetHandle audioClip, bool isLoop, float speed = 1)
  25. {
  26. if (audioClip == null)
  27. {
  28. return;
  29. }
  30. if (_assetHandle != null)
  31. {
  32. _assetHandle.Release();
  33. }
  34. IsPlay = true;
  35. _currPlayName = audioName;
  36. _assetHandle = audioClip;
  37. _audioSource.clip = _assetHandle.AssetObject<AudioClip>();
  38. _audioSource.loop = isLoop;
  39. _audioSource.pitch = speed;
  40. if (speed > 1)
  41. {
  42. _audioSource.outputAudioMixerGroup = AudioManager.Instance.AudioMixerGroup;
  43. _audioSource.outputAudioMixerGroup.audioMixer.SetFloat("path", 1f / speed);
  44. }
  45. else
  46. {
  47. _audioSource.outputAudioMixerGroup = null;
  48. }
  49. _audioSource.Play();
  50. if (!isLoop)
  51. {
  52. _timerEntity = TimerComponent.Instance.AddTimer((long) (_audioSource.clip.length * 1000L),
  53. delegate { Finish(); });
  54. }
  55. }
  56. public void Finish()
  57. {
  58. IsPlay = false;
  59. OnFinish?.Invoke();
  60. _audioSource.Stop();
  61. AudioManager.Instance.Recycle(this);
  62. TimerComponent.Instance.Remove(_timerEntity);
  63. _timerEntity = null;
  64. }
  65. public void Stop()
  66. {
  67. IsPlay = false;
  68. _audioSource.Stop();
  69. }
  70. public void Pause()
  71. {
  72. _audioSource.Pause();
  73. }
  74. public void UnPause()
  75. {
  76. _audioSource.UnPause();
  77. }
  78. public void Dispose()
  79. {
  80. if (_assetHandle != null)
  81. {
  82. _assetHandle.Release();
  83. }
  84. }
  85. }
  86. }