AudioManager_Script.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. using System.IO;
  6. using UnityEngine.Networking;
  7. public class AudioManager_Script : MonoBehaviour
  8. {
  9. private AudioSource greetingsAudio;
  10. private AudioSource commentAudio;
  11. private AudioSource sfxAudio;
  12. private Dictionary<String, int> clipCounts = new Dictionary<String, int>();
  13. void Awake()
  14. {
  15. greetingsAudio = gameObject.AddComponent<AudioSource>();
  16. greetingsAudio.playOnAwake = false;
  17. commentAudio = gameObject.AddComponent<AudioSource>();
  18. commentAudio.playOnAwake = false;
  19. sfxAudio = gameObject.AddComponent<AudioSource>();
  20. sfxAudio.playOnAwake = false;
  21. getClipCount("hurt");
  22. getClipCount("kill");
  23. getClipCount("death");
  24. }
  25. public bool playGreeting(AudioClip clip)
  26. {
  27. if (commentAudio.isPlaying) commentAudio.Stop();
  28. greetingsAudio.clip = clip;
  29. greetingsAudio.Play();
  30. return true;
  31. }
  32. public void playComment(string type)
  33. {
  34. if (!greetingsAudio.isPlaying && !commentAudio.isPlaying)
  35. {
  36. int clipCount = 0;
  37. clipCounts.TryGetValue(type, out clipCount);
  38. if (clipCount > 0) {
  39. int r = UnityEngine.Random.Range(0, clipCount);
  40. string path = "file://" + Application.streamingAssetsPath + "/Sounds/Comments/" + type + "/" + r + ".ogg";
  41. StartCoroutine(loadAndPlayFile(path, commentAudio));
  42. }
  43. }
  44. }
  45. public void playSfx(string name)
  46. {
  47. StartCoroutine(loadAndPlayFile("file://" + Application.streamingAssetsPath + "/Sounds/" + name + ".ogg", sfxAudio));
  48. }
  49. private IEnumerator loadAndPlayFile(string path, AudioSource player)
  50. {
  51. UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.OGGVORBIS);
  52. yield return request.SendWebRequest();
  53. if (!request.isNetworkError && !request.isHttpError) {
  54. player.clip = DownloadHandlerAudioClip.GetContent(request);
  55. player.Play();
  56. }
  57. }
  58. private void getClipCount(string type)
  59. {
  60. int clipCount = 0;
  61. foreach (string file in Directory.GetFiles(Application.streamingAssetsPath + "/Sounds/Comments/" + type + "/"))
  62. {
  63. if (file.EndsWith(".ogg"))
  64. {
  65. string fileName = Path.GetFileName(file).Replace(".ogg", "");
  66. #pragma warning disable 0649
  67. try
  68. {
  69. clipCount = Mathf.Clamp(int.Parse(fileName) + 1, clipCount, int.MaxValue);
  70. }
  71. catch (Exception e) {
  72. Debug.LogWarning(e);
  73. }
  74. #pragma warning restore 0649
  75. }
  76. }
  77. clipCounts.Add(type, clipCount);
  78. }
  79. }