VoiceManager.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. }
  65. public int GetClipLength()
  66. {
  67. if (player.clip != null)
  68. {
  69. return (int)Mathf.Ceil(player.clip.length);
  70. }
  71. return 0;
  72. }
  73. public void PlayOneShotCroutine(string path, Action action = null)
  74. {
  75. if (coroutine != null)
  76. {
  77. StopCoroutine(coroutine);
  78. }
  79. handle?.Release();
  80. if (_isOn)
  81. {
  82. if (YooAssets.CheckResExist(path))
  83. {
  84. coroutine = StartCoroutine(PlayOneShot(path, action));
  85. }
  86. else
  87. {
  88. action?.Invoke();
  89. }
  90. }
  91. }
  92. private IEnumerator PlayOneShot(string path, Action action = null)
  93. {
  94. //AudioClip clip = GFGAsset.Load<AudioClip>(path);
  95. handle = YooAssets.LoadAssetAsync<AudioClip>(path);
  96. yield return handle;
  97. player.clip = handle.AssetObject as AudioClip;
  98. player.Play();
  99. WaitForSound(action);
  100. }
  101. public void Stop()
  102. {
  103. player.Stop();
  104. }
  105. // 音频播放完成的回调函数
  106. private async Task WaitForSound(Action action = null)
  107. {
  108. int milliseconds = (int)(player.clip.length * 1000);
  109. await Task.Delay(milliseconds);
  110. action?.Invoke();
  111. }
  112. }
  113. }