AudioSourcePool.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 volume, 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. _audioSource.volume = volume;
  41. if (speed > 1)
  42. {
  43. _audioSource.outputAudioMixerGroup = AudioManager.Instance.AudioMixerGroup;
  44. _audioSource.outputAudioMixerGroup.audioMixer.SetFloat("path", 1f / speed);
  45. }
  46. else
  47. {
  48. _audioSource.outputAudioMixerGroup = null;
  49. }
  50. _audioSource.Play();
  51. if (!isLoop)
  52. {
  53. _timerEntity = TimerComponent.Instance.AddTimer((long) (_audioSource.clip.length * 1000L),
  54. delegate { Finish(); });
  55. }
  56. }
  57. public void Finish()
  58. {
  59. IsPlay = false;
  60. OnFinish?.Invoke();
  61. _audioSource.Stop();
  62. AudioManager.Instance.Recycle(this);
  63. TimerComponent.Instance.Remove(_timerEntity);
  64. _timerEntity = null;
  65. }
  66. public void Stop()
  67. {
  68. IsPlay = false;
  69. _audioSource.Stop();
  70. }
  71. public void Pause()
  72. {
  73. _audioSource.Pause();
  74. }
  75. public void UnPause()
  76. {
  77. _audioSource.UnPause();
  78. }
  79. public void Dispose()
  80. {
  81. if (_assetHandle != null)
  82. {
  83. _assetHandle.Release();
  84. }
  85. }
  86. }
  87. }