using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.Networking; namespace UltraCombos { public class SoundLoader : MonoBehaviour { [SerializeField] string folder; [SerializeField] List filenames = new List(); public List clips = new List(); AudioSource source = null; [SerializeField, Range(0, 1)] public float volumeScale = 1.0f; float target_volume = 1.0f; public UnityEvent onPlayFinished = new UnityEvent(); [Header("Debug")] public string info; private void Start() { if (filenames.Count == 0) { string filename = gameObject.name; LoadFile(filename); } else { foreach (var filename in filenames) { LoadFile(filename); } } source = gameObject.AddComponent(); source.playOnAwake = false; } void LoadFile(string filename) { string path = $"{Application.dataPath}/../../{folder}/{filename}"; if (System.IO.File.Exists(path)) { var ext = System.IO.Path.GetExtension(path); AudioType type = AudioType.UNKNOWN; if (ext.Equals(".AIF", System.StringComparison.CurrentCultureIgnoreCase)) { type = AudioType.AIFF; } else if (ext.Equals(".WAV", System.StringComparison.CurrentCultureIgnoreCase)) { type = AudioType.WAV; } if (type != AudioType.UNKNOWN) { StartCoroutine(LoadAudioFile($"file://{path}", type)); } else { } } } private void Update() { source.volume = Mathf.Lerp(source.volume, target_volume * volumeScale, Time.deltaTime); if (source.isPlaying && target_volume > 0.5f && source.clip != null) { info = $"{source.time:F1}/{source.clip.length:F1}"; if (source.clip.length - source.time < 1.0f) { onPlayFinished.Invoke(); info = "play finished"; } } } [ContextMenu("Play Audio")] public void PlayOneShot() { if (clips.Count == 0) return; source.PlayOneShot(clips[Random.Range(0, clips.Count)], volumeScale); } public void FadeIn() { if (clips.Count == 0) return; source.clip = clips[0]; source.Play(); source.volume = 0.0f; target_volume = 1.0f; } public void FadeOut() { if (clips.Count == 0) return; target_volume = 0.0f; } IEnumerator LoadAudioFile(string uri, AudioType type) { using (var www = UnityWebRequestMultimedia.GetAudioClip(uri, type)) { yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { using (var hanlder = www.downloadHandler as DownloadHandlerAudioClip) { if (hanlder != null) { clips.Add(hanlder.audioClip); } } } yield return null; } } } }