MusicManager.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System.Collections;
  2. using UnityEngine;
  3. using GFGGame.Launcher;
  4. using YooAsset;
  5. namespace GFGGame
  6. {
  7. public class MusicManager : SingletonMonoBase<MusicManager>
  8. {
  9. private AudioSource player;
  10. private string currentName;
  11. private AssetOperationHandle handle;
  12. private Coroutine coroutine;
  13. private bool _isOn = true;
  14. public bool isOn
  15. {
  16. get
  17. {
  18. return _isOn;
  19. }
  20. set
  21. {
  22. if(_isOn != value)
  23. {
  24. _isOn = value;
  25. if(_isOn)
  26. {
  27. if(currentName != null)
  28. {
  29. PlayCroutine(currentName, true);
  30. }
  31. }
  32. else
  33. {
  34. Stop();
  35. }
  36. LocalCache.SetBool(LauncherConfig.MUSIC_KEY, _isOn);
  37. }
  38. }
  39. }
  40. private void Awake()
  41. {
  42. player = this.gameObject.AddComponent<AudioSource>();
  43. player.loop = true;
  44. isOn = LocalCache.GetBool(LauncherConfig.MUSIC_KEY, true);
  45. }
  46. private void Start()
  47. {
  48. }
  49. private void Update()
  50. {
  51. }
  52. public void PlayCroutine(string path, bool must = false)
  53. {
  54. if(currentName != path || must)
  55. {
  56. currentName = path;
  57. if(coroutine != null)
  58. {
  59. StopCoroutine(coroutine);
  60. }
  61. handle?.Release();
  62. if (_isOn)
  63. {
  64. coroutine = StartCoroutine(Play(path));
  65. }
  66. }
  67. }
  68. private IEnumerator Play(string path)
  69. {
  70. //AudioClip clip = GFGAsset.Load<AudioClip>(path);
  71. handle = YooAssets.LoadAssetAsync<AudioClip>(path);
  72. yield return handle;
  73. player.clip = handle.AssetObject as AudioClip;
  74. player.Play();
  75. }
  76. public float GetSoundTime()
  77. {
  78. if (player.clip != null)
  79. {
  80. return player.clip.length;
  81. }
  82. return 0;
  83. }
  84. public void Pause()
  85. {
  86. player.Pause();
  87. }
  88. public void UnPause()
  89. {
  90. player.UnPause();
  91. }
  92. public void Stop()
  93. {
  94. handle.Release();
  95. player.Stop();
  96. }
  97. }
  98. }