Is OnAudioFilterRead just a pro feature?

Hi guys,
in order to test the functionality of OnAudioFilterRead I have inserted the following in a script in a bare-bones demo application:

void OnAudioFilterRead (float[] data, int channels)  {
  for (int i = 0; i < data.Length; ++i) {
	float x = UnityEngine.Random.Range(-1, 1);
	data *= x;*
  • }*
    

}
I would expect noise to come fro the iPhone speaker, but everything is dead silent. So I wonder: is this a pro feature, but it fails silently? I can see that the method gets actually called. Otherwise: is there something else that I need to know in order to be able to synthesize from OnAudioFIlterRead? for example a setting, or something related to components? I am an audio developer, I am new to Unity3d. Thanks

Hello,

I think you are calling the Range(int,int) which return a integer so it is normal if you don’t hear anything (it generates only -1 or 1), maybe try:

void OnAudioFilterRead (float[] data, int channels)  {
  for (int i = 0; i < data.Length; ++i) {
    float x = UnityEngine.Random.Range(-1f, 1f);
    data *= x;*

}
}

While a bit late, I will post this for future reference.

You should include an Audio Source component.

A basic note (not a pure sinewave in this case) could be produced by the following script.

(m_frequency is the frequency of the note you want, and sampling_frequency can be obtained from AudioSettings.outputSampleRate; it usually is 48000)

private void OnAudioFilterRead(float[] data, int channels)
{
    if (!running) return;

    // update increment in case frequency has changed
    for (int i = 0; i < 4; i++)
    {
        m_increments <em>= m_frequency * Mathf.Pow(2, i) * Mathf.PI / sampling_frequency;</em>

}

// Fill the data buffer
for (int i = 0; i < data.Length; i = i + channels)
{
float l_output = 0.0f;

  •  // Generate the Tone/data*
    
  •  for (int n = 0; n < 4; n++)*
    
  •  {*
    

m_phases[n] += m_increments[n];
if (m_phases[n] > 2 * Mathf.PI) m_phases[n] -= 2 * Mathf.PI;

l_output += m_gain * m_harmonicAmp[n] * Mathf.Sin(m_phases[n]);

  •  }*
    
  •  // this is where we copy audio data to make them “available” to Unity*
    

data += l_output;

* // if we have stereo, we copy the mono data to each channel*
_ if (channels == 2) data[i + 1] = data*;
}
}*_

This snippet can generate a fiery noise:
(Snippet source: [Develop-online.net][1])
using UnityEngine;
using System; // Needed for Random

public class Noise : MonoBehaviour
{
// un-optimized version of a noise generator
private System.Random RandomNumber = new System.Random();
public float offset = 0;

void OnAudioFilterRead(float[] data, int channels)
{
for (int i = 0; i < data.Length; i++)
{
data = offset -1.0f + (float)RandomNumber.NextDouble()*2.0f;
}
}
}
_*[1]: http://www.develop-online.net/tools-and-tech/procedural-audio-with-unity/0117433*_