AudioChannelMixer.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using UnityEngine;
  2. //-----------------------------------------------------------------------------
  3. // Copyright 2019-2022 RenderHeads Ltd. All rights reserved.
  4. //-----------------------------------------------------------------------------
  5. namespace RenderHeads.Media.AVProVideo
  6. {
  7. /// Allows per-channel volume control
  8. /// Currently supported on Windows and UWP (Media Foundation API only), macOS, iOS, tvOS and Android (ExoPlayer API only)
  9. [AddComponentMenu("AVPro Video/Audio Channel Mixer", 401)]
  10. [HelpURL("https://www.renderheads.com/products/avpro-video/")]
  11. public class AudioChannelMixer : MonoBehaviour
  12. {
  13. const int MaxChannels = 8;
  14. [Range(0f, 1f)]
  15. [SerializeField] float[] _channels = null;
  16. /// Range 0.0 to 1.0
  17. public float[] Channel
  18. {
  19. get { return _channels; }
  20. set { _channels = value; }
  21. }
  22. void Reset()
  23. {
  24. _channels = new float[MaxChannels];
  25. for (int i = 0; i < MaxChannels; i++)
  26. {
  27. _channels[i] = 1f;
  28. }
  29. }
  30. void ChangeChannelCount(int numChannels)
  31. {
  32. float[] channels = new float[numChannels];
  33. if (_channels != null && _channels.Length != 0)
  34. {
  35. for (int i = 0; i < channels.Length; i++)
  36. {
  37. if (i < _channels.Length)
  38. {
  39. channels[i] = _channels[i];
  40. }
  41. else
  42. {
  43. channels[i] = 1f;
  44. }
  45. }
  46. }
  47. else
  48. {
  49. for (int i = 0; i < numChannels; i++)
  50. {
  51. channels[i] = 1f;
  52. }
  53. }
  54. _channels = channels;
  55. }
  56. void OnAudioFilterRead(float[] data, int channels)
  57. {
  58. if (channels != _channels.Length)
  59. {
  60. ChangeChannelCount(channels);
  61. }
  62. int k = 0;
  63. int numSamples = data.Length / channels;
  64. for (int j = 0; j < numSamples; j++)
  65. {
  66. for (int i = 0; i < channels; i++)
  67. {
  68. data[k] *= _channels[i];
  69. k++;
  70. }
  71. }
  72. }
  73. }
  74. }