using System.Collections; using UnityEngine; using GFGGame.Launcher; using YooAsset; namespace GFGGame { public class MusicManager : SingletonMonoBase { private AudioSource player; private string currentName; private AssetOperationHandle handle; private Coroutine coroutine; private float normalVolumn = 1f; private float curVolume = 1f; private float changeValue = 0.01f; private bool _isOn = true; public bool isOn { get { return _isOn; } set { if (_isOn != value) { _isOn = value; if (_isOn) { if (currentName != null) { PlayCroutine(currentName, true); } } else { Stop(); } LocalCache.SetBool(LauncherConfig.MUSIC_KEY, _isOn); } } } private void Awake() { player = this.gameObject.AddComponent(); player.loop = true; isOn = LocalCache.GetBool(LauncherConfig.MUSIC_KEY, true); } private void Start() { } private void Update() { if (player.clip == null || !isOn) { return; } if (VoiceManager.Instance.IsPlaying()) { curVolume = 0.17f; } else { curVolume = normalVolumn; } if (player.volume != curVolume) { player.volume = Mathf.Lerp(player.volume, curVolume, changeValue); if (Mathf.Abs(player.volume - curVolume) <= 0.05) { player.volume = curVolume; } } } public void PlayCroutine(string path, bool must = false, float volume = 1.0f) { if (currentName != path || must) { currentName = path; if (coroutine != null) { StopCoroutine(coroutine); } handle?.Release(); if (_isOn) { coroutine = StartCoroutine(Play(path, volume)); } } } private IEnumerator Play(string path, float volume = 1.0f) { //AudioClip clip = GFGAsset.Load(path); handle = YooAssets.LoadAssetAsync(path); yield return handle; player.clip = handle.AssetObject as AudioClip; player.volume = volume; player.Play(); } public float GetSoundTime() { if (player.clip != null) { return player.clip.length; } return 0; } public void Pause() { player.Pause(); } public void UnPause() { player.UnPause(); } public void Stop() { handle?.Release(); player?.Stop(); } public void SetVolume(float volume) { player.volume = volume; } public void SetNormalVolumn(float volume) { normalVolumn = volume; } } }