LowLatencyLipSyncContext.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using UnityEngine;
  3. namespace XVI.AniLipSync
  4. {
  5. public class LowLatencyLipSyncContext : OVRLipSyncContextBase
  6. {
  7. private OVRLipSync.VariableData m_Variable
  8. {
  9. get
  10. {
  11. return GameMain.Instance.LipSyncMgr.Variable;
  12. }
  13. }
  14. public override void Init()
  15. {
  16. base.Init();
  17. this.m_MicInput = base.GetComponent<OVRLipSyncMicInput>();
  18. this.processBuffer = new float[OVRLipSync.BuffSize];
  19. this.microphoneBuffer = new float[OVRLipSync.SamplingRate * 10];
  20. }
  21. private void Update()
  22. {
  23. if (!this.audioSource.clip)
  24. {
  25. return;
  26. }
  27. int position = Microphone.GetPosition(this.m_MicInput.selectedDevice);
  28. if (position < 0 || this.head == position)
  29. {
  30. return;
  31. }
  32. this.audioSource.clip.GetData(this.microphoneBuffer, 0);
  33. while (LowLatencyLipSyncContext.GetDataLength(this.microphoneBuffer.Length, this.head, position) > this.processBuffer.Length)
  34. {
  35. int num = this.microphoneBuffer.Length - this.head;
  36. if (num < this.processBuffer.Length)
  37. {
  38. Array.Copy(this.microphoneBuffer, this.head, this.processBuffer, 0, num);
  39. Array.Copy(this.microphoneBuffer, 0, this.processBuffer, num, this.processBuffer.Length - num);
  40. }
  41. else
  42. {
  43. Array.Copy(this.microphoneBuffer, this.head, this.processBuffer, 0, this.processBuffer.Length);
  44. }
  45. float[] array = new float[this.processBuffer.Length];
  46. Array.Copy(this.processBuffer, array, array.Length);
  47. for (int i = 0; i < array.Length; i++)
  48. {
  49. array[i] *= this.m_Variable.MicSensitivity;
  50. }
  51. OVRLipSync.ProcessFrame(base.Context, array, OVRLipSync.Flags.None, base.Frame);
  52. this.head += this.processBuffer.Length;
  53. if (this.head > this.microphoneBuffer.Length)
  54. {
  55. this.head -= this.microphoneBuffer.Length;
  56. }
  57. }
  58. }
  59. public float GetMicVolume()
  60. {
  61. float num = 0f;
  62. foreach (float f in this.processBuffer)
  63. {
  64. num += Mathf.Abs(f);
  65. }
  66. return num / (float)this.processBuffer.Length;
  67. }
  68. private static int GetDataLength(int bufferLength, int head, int tail)
  69. {
  70. if (head < tail)
  71. {
  72. return tail - head;
  73. }
  74. return bufferLength - head + tail;
  75. }
  76. private AudioClip clip;
  77. private int head;
  78. private float[] processBuffer = new float[512];
  79. private float[] microphoneBuffer = new float[441000];
  80. private OVRLipSyncMicInput m_MicInput;
  81. }
  82. }