AudioSourcePool.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. private float maxTime;
  15. public string CurrPlayName
  16. {
  17. get { return _currPlayName; }
  18. }
  19. public string _currPlayName;
  20. public void Init(Transform root)
  21. {
  22. GameObject gameObject = new GameObject();
  23. _audioSource = gameObject.AddComponent<AudioSource>();
  24. gameObject.transform.SetParent(root);
  25. }
  26. public void Play(string audioName, AssetHandle audioClip, bool isLoop, float volume, float speed = 1)
  27. {
  28. if (audioClip == null)
  29. {
  30. return;
  31. }
  32. // if (_assetHandle != null)
  33. // {
  34. // _assetHandle.Release();
  35. // }
  36. IsPlay = true;
  37. _currPlayName = audioName;
  38. // _assetHandle = audioClip;
  39. _audioSource.clip = audioClip.AssetObject<AudioClip>();
  40. _audioSource.loop = isLoop;
  41. _audioSource.pitch = speed;
  42. _audioSource.volume = volume;
  43. if (speed > 1)
  44. {
  45. _audioSource.outputAudioMixerGroup = AudioManager.Instance.AudioMixerGroup;
  46. _audioSource.outputAudioMixerGroup.audioMixer.SetFloat("path", 1f / speed);
  47. }
  48. else
  49. {
  50. _audioSource.outputAudioMixerGroup = null;
  51. }
  52. _audioSource.Play();
  53. maxTime = _audioSource.clip.length;
  54. if (!isLoop)
  55. {
  56. _timerEntity = TimerComponent.Instance.AddTimer((long)(maxTime * 1000L),
  57. delegate { Finish(); });
  58. }
  59. }
  60. public float Progress()
  61. {
  62. return _audioSource.time / maxTime;
  63. }
  64. public void Finish()
  65. {
  66. IsPlay = false;
  67. OnFinish?.Invoke();
  68. _audioSource.Stop();
  69. AudioManager.Instance.Recycle(this);
  70. TimerComponent.Instance.Remove(_timerEntity);
  71. _timerEntity = null;
  72. }
  73. public void Stop()
  74. {
  75. IsPlay = false;
  76. _audioSource.Stop();
  77. }
  78. public void Pause()
  79. {
  80. _audioSource.Pause();
  81. }
  82. public void UnPause()
  83. {
  84. _audioSource.UnPause();
  85. }
  86. public void Dispose()
  87. {
  88. }
  89. }
  90. }