using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.IO; using UnityEngine.Networking; public class AudioManager_Script : MonoBehaviour { private AudioSource greetingsAudio; private AudioSource commentAudio; private AudioSource sfxAudio; private Dictionary clipCounts = new Dictionary(); void Awake() { greetingsAudio = gameObject.AddComponent(); greetingsAudio.playOnAwake = false; commentAudio = gameObject.AddComponent(); commentAudio.playOnAwake = false; sfxAudio = gameObject.AddComponent(); sfxAudio.playOnAwake = false; getClipCount("hurt"); getClipCount("kill"); getClipCount("death"); } public bool playGreeting(AudioClip clip) { if (commentAudio.isPlaying) commentAudio.Stop(); greetingsAudio.clip = clip; greetingsAudio.Play(); return true; } public void playComment(string type) { if (!greetingsAudio.isPlaying && !commentAudio.isPlaying) { int clipCount = 0; clipCounts.TryGetValue(type, out clipCount); if (clipCount > 0) { int r = UnityEngine.Random.Range(0, clipCount); string path = "file://" + Application.streamingAssetsPath + "/Sounds/Comments/" + type + "/" + r + ".ogg"; StartCoroutine(loadAndPlayFile(path, commentAudio)); } } } public void playSfx(string name) { StartCoroutine(loadAndPlayFile("file://" + Application.streamingAssetsPath + "/Sounds/" + name + ".ogg", sfxAudio)); } private IEnumerator loadAndPlayFile(string path, AudioSource player) { UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.OGGVORBIS); yield return request.SendWebRequest(); if (!request.isNetworkError && !request.isHttpError) { player.clip = DownloadHandlerAudioClip.GetContent(request); player.Play(); } } private void getClipCount(string type) { int clipCount = 0; foreach (string file in Directory.GetFiles(Application.streamingAssetsPath + "/Sounds/Comments/" + type + "/")) { if (file.EndsWith(".ogg")) { string fileName = Path.GetFileName(file).Replace(".ogg", ""); #pragma warning disable 0649 try { clipCount = Mathf.Clamp(int.Parse(fileName) + 1, clipCount, int.MaxValue); } catch (Exception e) { Debug.LogWarning(e); } #pragma warning restore 0649 } } clipCounts.Add(type, clipCount); } }