Created
April 4, 2019 19:24
-
-
Save maxweisel/cc0bf9a88e5dcec37863c25118aecad8 to your computer and use it in GitHub Desktop.
Get the most recent X samples from the Unity microphone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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