123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 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<String, int> clipCounts = new Dictionary<String, int>();
- void Awake()
- {
- greetingsAudio = gameObject.AddComponent<AudioSource>();
- greetingsAudio.playOnAwake = false;
- commentAudio = gameObject.AddComponent<AudioSource>();
- commentAudio.playOnAwake = false;
- sfxAudio = gameObject.AddComponent<AudioSource>();
- 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);
- }
- }
|