SoundManager.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using Animancer;
  2. using ET;
  3. using ET.Client;
  4. using ET.EventType;
  5. using Mono;
  6. using System.Text.RegularExpressions;
  7. using UnityEngine;
  8. [Event(SceneType.None)]
  9. public class PlayBGMHandler : BEvent<ET.EventType.PlayBgm>
  10. {
  11. public override void OnEvent(PlayBgm args)
  12. {
  13. if (args.Play)
  14. {
  15. SoundManager.Instance.PlayBgm(args.Bgm).Coroutine();
  16. }
  17. else
  18. {
  19. SoundManager.Instance.StopBgm();
  20. }
  21. }
  22. }
  23. public class SoundManager : Singleton<SoundManager>, ISingletonAwake
  24. {
  25. public AudioSource UnityAudioSource { get; private set; }
  26. public bool Mute
  27. {
  28. get { return UnityAudioSource.mute; }
  29. set { UnityAudioSource.mute = value; }
  30. }
  31. public float Volume
  32. {
  33. get { return UnityAudioSource.volume; }
  34. set { UnityAudioSource.volume = value; }
  35. }
  36. public void Awake()
  37. {
  38. UnityAudioSource = GameObject.Find("/Global/Audio").GetComponent<AudioSource>();
  39. UnityAudioSource.loop = true;
  40. UnityAudioSource.volume = 1f;
  41. UnityAudioSource.playOnAwake = false;
  42. var mute = GameSetting.Instance.GetBool(GameSetting.Sets.Mute_int);
  43. UnityAudioSource.mute = mute;
  44. }
  45. public async ETTask PlayBgm(string name)
  46. {
  47. Log.Debug($"play bgm:{name}");
  48. var ac = await GameObjectPool.Instance.AcquireSound(name);
  49. UnityAudioSource.clip = ac;
  50. UnityAudioSource.Play();
  51. }
  52. public void StopBgm()
  53. {
  54. Log.Debug("stop bgm");
  55. UnityAudioSource.Stop();
  56. }
  57. public async ETTask PlayUISound(string name, float duration = -1f)
  58. {
  59. var key = name;
  60. var m = Regex.Match(key, "/?res/sound/.*/([\\w_\\d]+)\\.assetbundles$");
  61. if (m.Success)
  62. {
  63. key = m.Groups[1].Value.ToLower();
  64. }
  65. var ac = await GameObjectPool.Instance.AcquireSound(key);
  66. UnityAudioSource.PlayOneShot(ac);
  67. }
  68. //TODO:实现3D音源随物体移动
  69. public async ETTask Play3DSound(string name, Vector3 pos, float duration = -1f)
  70. {
  71. var key = name;
  72. var m = Regex.Match(key, "/?res/sound/.*/([\\w_\\d]+)\\.assetbundles$");
  73. if (m.Success)
  74. {
  75. key = m.Groups[1].Value.ToLower();
  76. }
  77. //Log.Debug($"play 3dsound: {key}");
  78. var ac = await GameObjectPool.Instance.AcquireSound(key);
  79. //AudioSource.PlayClipAtPoint(ac, pos);
  80. UnityAudioSource.PlayOneShot(ac);
  81. }
  82. }