8 [RequireComponent(typeof(AudioSource))]
20 public float InputGain = 1;
32 public bool AutomaticallyStartStream =
true;
37 public bool PlaybackMicrophoneAudioSource =
true;
42 public string SaveFileName =
"MicrophoneTest.wav";
47 private float averageAmplitude;
53 private float minObjectScale = .3f;
55 private bool isRunning;
59 get {
return isRunning; }
69 private void OnAudioFilterRead(
float[] buffer,
int numChannels)
74 float sumOfValues = 0;
77 for (
int i = 0; i < buffer.Length; i++)
79 if (
float.IsNaN(buffer[i]))
84 buffer[i] = Mathf.Clamp(buffer[i], -1f, 1f);
85 sumOfValues += Mathf.Clamp01(Mathf.Abs(buffer[i]));
87 averageAmplitude = sumOfValues / buffer.Length;
90 private void OnEnable()
100 if (!PlaybackMicrophoneAudioSource)
102 gameObject.GetComponent<AudioSource>().volume = 0;
105 if (AutomaticallyStartStream)
110 print(
"MicStream selector demo");
111 print(
"press Q to start stream to audio source, W will stop that stream");
112 print(
"press A to start a recording and S to stop that recording and save it to a wav file.");
113 print(
"Since this all goes through the AudioSource, you can mute the mic while using it there, or do anything else you would do with an AudioSource");
114 print(
"In this demo, we start the stream automatically, and then change the size of the GameObject based on microphone signal amplitude");
118 private void Update()
122 if (Input.GetKeyDown(KeyCode.Q))
126 else if (Input.GetKeyDown(KeyCode.W))
130 else if (Input.GetKeyDown(KeyCode.A))
134 else if (Input.GetKeyDown(KeyCode.S))
137 Debug.Log(
"Saved microphone audio to " + outputPath);
141 gameObject.transform.localScale =
new Vector3(minObjectScale + averageAmplitude, minObjectScale + averageAmplitude, minObjectScale + averageAmplitude);
144 private void OnApplicationPause(
bool pause)
149 private void OnDisable()
154 private void OnDestroy()
160 private void OnApplicationFocus(
bool focused)
167 private static void CheckForErrorOnCall(
int returnCode)