Hi,
i’m developing a real time streaming chat and stumbled upon this problem.
The code is much more complex but for the sake of simplicity i’ll summarize what i’m doing and expose just what is giving me the problem.
If i record the mic like this, on the client side:
void Init_Mic()
{
audioSource.clip = Microphone.Start(null, true, 120, 44100);
audioSource.loop = true;
audioSource.Play();
}
void OnAudioFilterRead(float[] data, int channels)
{
samples = new float[data.Length];
for (int x = 0; x < data.Length; x++)
{
samples[x] = data[x];
}
client.ReceiveData(samples);
}
It works GREAT. Minimum delay and no artifacts. But of course i need to compress the data through an encoder before sending the packets to the network socket. To do such a thing, i need to resample my microphone input to 8000hz, or 16000hz for example (Speex or Opus encoders i.e.) and here come the problems.
If i simply change the microphone clip samplerate from 44100hz to 8000hz (or any other sampling rate for that matter), onaudiofilterread completely breaks and doesn’t give me the resulting data correctly (the input audio is glitchy like some data is missing).
The only way to get correct samples from a 8000hz mic input is to do something like this:
if (Microphone.GetPosition(null) >= last_pos + mic_samples_buffer)
{
float[] samples = new float[mic_samples_buffer];
goAudioSource.clip.GetData(samples, last_pos);
bufferHandler.AddArrayToBuffer(samples);
last_pos = Microphone.GetPosition(null);
}
Getting samples through GetData() function of the audioclip is not the solution tho because is slow and can only run on the main thread (i.e. Update()).
Also, i tried to change the global outputSampleRate of the project (and tried various dsp sizes) but the problem persists. The samplerate that works is 44100.
It looks like OnAudioFilter doesn’t adapts anymore to the samplingRate changes.
I’m absolutely sure it was POSSIBLE, previously (i’ve been working as an audio designer / coder for years in a commercial company) just by settings an empty clip with different samplingRate on the audiosource on the same object where the onAudioFilter code runs.
Can anybody confirm this is a bug?
In case, can anybody point me to an older Unity version where this was used to work?
I’ve been pulling my hair on this for days… ![]()