AudioSourcePool.cs 2.5 KB

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