CombinedAudioEventReference.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. using Meta.WitAi.Events;
  9. using Meta.WitAi.Events.UnityEventListeners;
  10. using Meta.WitAi.Interfaces;
  11. using UnityEngine.Events;
  12. namespace Meta.WitAi.ServiceReferences
  13. {
  14. /// <summary>
  15. /// Finds all audio event listeners in the scene and subscribes to them.
  16. /// This is good for creating generic attention systems that are shown for
  17. /// the same way for any voice based service active in the scene.
  18. /// </summary>
  19. //[Tooltip("Finds all voice based services and listens for changes in their audio input state.")]
  20. public class CombinedAudioEventReference : AudioInputServiceReference, IAudioInputEvents
  21. {
  22. public override IAudioInputEvents AudioEvents => this;
  23. private WitMicLevelChangedEvent _onMicAudioLevelChanged = new WitMicLevelChangedEvent();
  24. private UnityEvent _onMicStartedListening = new UnityEvent();
  25. private UnityEvent _onMicStoppedListening = new UnityEvent();
  26. private AudioEventListener[] _sourceListeners;
  27. private void Awake()
  28. {
  29. #if UNITY_2020_1_OR_NEWER
  30. _sourceListeners = FindObjectsOfType<AudioEventListener>(true);
  31. #else
  32. _sourceListeners = FindObjectsOfType<AudioEventListener>();
  33. #endif
  34. }
  35. private void OnEnable()
  36. {
  37. foreach (var listener in _sourceListeners)
  38. {
  39. listener.OnMicAudioLevelChanged.AddListener(OnMicAudioLevelChanged.Invoke);
  40. listener.OnMicStartedListening.AddListener(OnMicStartedListening.Invoke);
  41. listener.OnMicStoppedListening.AddListener(OnMicStoppedListening.Invoke);
  42. }
  43. }
  44. private void OnDisable()
  45. {
  46. foreach (var listener in _sourceListeners)
  47. {
  48. listener.OnMicAudioLevelChanged.RemoveListener(OnMicAudioLevelChanged.Invoke);
  49. listener.OnMicStartedListening.RemoveListener(OnMicStartedListening.Invoke);
  50. listener.OnMicStoppedListening.RemoveListener(OnMicStoppedListening.Invoke);
  51. }
  52. }
  53. public WitMicLevelChangedEvent OnMicAudioLevelChanged => _onMicAudioLevelChanged;
  54. public UnityEvent OnMicStartedListening => _onMicStartedListening;
  55. public UnityEvent OnMicStoppedListening => _onMicStoppedListening;
  56. }
  57. }