Skip to content

Instantly share code, notes, and snippets.

@maxweisel
Created April 4, 2019 19:24
Show Gist options
  • Save maxweisel/cc0bf9a88e5dcec37863c25118aecad8 to your computer and use it in GitHub Desktop.
Save maxweisel/cc0bf9a88e5dcec37863c25118aecad8 to your computer and use it in GitHub Desktop.
Get the most recent X samples from the Unity microphone
private void Awake() {
_deviceName = "";
_microphone = Microphone.Start(_deviceName, true, 1, frequency);
if (_microphone == null) {
Debug.LogError("Unity returned a null microphone instance :S");
return;
}
_numberOfChannels = _microphone.channels;
_sampleCount = _microphone.samples;
}
public bool GetMostRecentData(float[] buffer) {
if (_microphone == null) {
Debug.LogError("Uh oh, we don't have a microphone to read samples from bruv.");
return;
}
// Number of samples to read into the supplied buffer.
int numberOfSamplesToRead = buffer.Length / _numberOfChannels;
if (numberOfSamplesToRead > _sampleCount) {
Debug.LogError("Reading microphone audio data. Supplied buffer is larger than the microphone buffer. (" + buffer.Length + ", " + _sampleCount * _numberOfChannels + ")");
return false;
}
int localWriteHeadPosition = Microphone.GetPosition(_deviceName);
int localReadHeadPosition = localWriteHeadPosition - numberOfSamplesToRead;
while (localReadHeadPosition >= _sampleCount)
localReadHeadPosition -= _sampleCount;
while (localReadHeadPosition < 0)
localReadHeadPosition += _sampleCount;
return _microphone.GetData(buffer, localReadHeadPosition);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment