using UnityEngine; using FairyGUI; using GFGGame.Launcher; using YooAsset; using System.Collections; using System.Threading.Tasks; using System; namespace GFGGame { public class VoiceManager : SingletonMonoBase { private AudioSource player; private AssetOperationHandle handle; private Coroutine coroutine; private bool _isOn = true; public bool isOn { get { return _isOn; } set { if (_isOn != value) { _isOn = value; if (_isOn) { GRoot.inst.soundVolume = 1; } else { GRoot.inst.soundVolume = 0; Stop(); } LocalCache.SetBool(LauncherConfig.SOUND_KEY, _isOn); } } } private void Awake() { player = this.gameObject.AddComponent(); isOn = LocalCache.GetBool(LauncherConfig.SOUND_KEY, true); } public void LoadRes(string path) { if (!YooAssets.CheckResExist(path)) { return; } handle = YooAssets.LoadAssetSync(path); player.clip = handle.AssetObject as AudioClip; } public void PlayVoice() { if(player.clip != null) { player.Play(); } } public void StopVoice() { player.Stop(); } public int GetClipLength() { if (player.clip != null) { return (int)Mathf.Ceil(player.clip.length); } return 0; } public void PlayOneShotCroutine(string path, Action action = null) { if (coroutine != null) { StopCoroutine(coroutine); } handle?.Release(); if (_isOn) { if (YooAssets.CheckResExist(path)) { coroutine = StartCoroutine(PlayOneShot(path, action)); } else { action?.Invoke(); } } } private IEnumerator PlayOneShot(string path, Action action = null) { //AudioClip clip = GFGAsset.Load(path); handle = YooAssets.LoadAssetAsync(path); yield return handle; player.clip = handle.AssetObject as AudioClip; player.Play(); WaitForSound(action); } public void Stop() { player.Stop(); } // 音频播放完成的回调函数 private async Task WaitForSound(Action action = null) { int milliseconds = (int)(player.clip.length * 1000); await Task.Delay(milliseconds); action?.Invoke(); } } }