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) { //player.volume = 1; } else { //player.volume = 0; Stop(); } LocalCache.SetBool(LauncherConfig.VOICE_KEY, _isOn); } } } private void Awake() { player = this.gameObject.AddComponent(); player.priority = 256; //设置这个声音会大一些 player.spatialBlend = 1f; isOn = LocalCache.GetBool(LauncherConfig.VOICE_KEY, true); player.volume = LocalCache.GetFloat(LauncherConfig.VOICE_VOLUMN_KEY, 1); } public void LoadRes(string path) { if (!isOn || !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(); handle = null; player.clip = null; } public float GetClipLength() { if (player.clip != null) { return player.clip.length; } return 0; } public float GetClipRemainingLength() { if (player.clip != null) { return Mathf.Ceil(player.clip.length - player.time); } 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(); } public bool IsPlaying() { return player.isPlaying; } public void SetVolumn(float volumn) { player.volume = volumn; } public float GetVolumn() { return player.volume; } } }