VoiceManager.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. using UnityEngine;
  2. using FairyGUI;
  3. using GFGGame.Launcher;
  4. using YooAsset;
  5. using System.Collections;
  6. using System.Threading.Tasks;
  7. using System;
  8. namespace GFGGame
  9. {
  10. public class VoiceManager : SingletonMonoBase<VoiceManager>
  11. {
  12. private AudioSource player;
  13. private AssetOperationHandle handle;
  14. private Coroutine coroutine;
  15. private bool _isOn = true;
  16. public bool isOn
  17. {
  18. get
  19. {
  20. return _isOn;
  21. }
  22. set
  23. {
  24. if (_isOn != value)
  25. {
  26. _isOn = value;
  27. if (_isOn)
  28. {
  29. GRoot.inst.soundVolume = 1;
  30. }
  31. else
  32. {
  33. GRoot.inst.soundVolume = 0;
  34. Stop();
  35. }
  36. LocalCache.SetBool(LauncherConfig.SOUND_KEY, _isOn);
  37. }
  38. }
  39. }
  40. private void Awake()
  41. {
  42. player = this.gameObject.AddComponent<AudioSource>();
  43. isOn = LocalCache.GetBool(LauncherConfig.SOUND_KEY, true);
  44. }
  45. public void LoadRes(string path)
  46. {
  47. if (!YooAssets.CheckResExist(path))
  48. {
  49. return;
  50. }
  51. handle = YooAssets.LoadAssetSync<AudioClip>(path);
  52. player.clip = handle.AssetObject as AudioClip;
  53. }
  54. public void PlayVoice()
  55. {
  56. if(player.clip != null)
  57. {
  58. player.Play();
  59. }
  60. }
  61. public void StopVoice()
  62. {
  63. player.Stop();
  64. handle = null;
  65. player.clip = null;
  66. }
  67. public int GetClipLength()
  68. {
  69. if (player.clip != null)
  70. {
  71. return (int)Mathf.Ceil(player.clip.length);
  72. }
  73. return 0;
  74. }
  75. public void PlayOneShotCroutine(string path, Action action = null)
  76. {
  77. if (coroutine != null)
  78. {
  79. StopCoroutine(coroutine);
  80. }
  81. handle?.Release();
  82. if (_isOn)
  83. {
  84. if (YooAssets.CheckResExist(path))
  85. {
  86. coroutine = StartCoroutine(PlayOneShot(path, action));
  87. }
  88. else
  89. {
  90. action?.Invoke();
  91. }
  92. }
  93. }
  94. private IEnumerator PlayOneShot(string path, Action action = null)
  95. {
  96. //AudioClip clip = GFGAsset.Load<AudioClip>(path);
  97. handle = YooAssets.LoadAssetAsync<AudioClip>(path);
  98. yield return handle;
  99. player.clip = handle.AssetObject as AudioClip;
  100. player.Play();
  101. WaitForSound(action);
  102. }
  103. public void Stop()
  104. {
  105. player.Stop();
  106. }
  107. // 音频播放完成的回调函数
  108. private async Task WaitForSound(Action action = null)
  109. {
  110. int milliseconds = (int)(player.clip.length * 1000);
  111. await Task.Delay(milliseconds);
  112. action?.Invoke();
  113. }
  114. }
  115. }