ARTICLE AD BOX
I'm making a music maker with c# in Unity and I have these methods that allow me to play individual frequencies in a sequence by adjusting the variables in a coroutine.
void OnAudioFilterRead(float[] data, int channels) { if (playing) { data = PlaySineWave(freq, realAmp, data, channels); } else { data = new float[0]; } } public float[] PlaySineWave(float frequency, float amplitude, float[] data, int channels) { double phaseIncrement = frequency / sampleRate; for (int sample = 0; sample < data.Length; sample += channels) { float value = Mathf.Sin((float)phase * 2 * Mathf.PI) * amplitude * saturation; phase = (phase + phaseIncrement) % 1; for (int chan = 0; chan < channels; chan++) { data[sample + chan] = value; } } return data; }This code works for playing individual frequencies and I am now trying to renovate what I have so that it can work with an array of frequencies that play at the same time. I know that frequencies can be combined by simply adding them together, so my approach was to reset the data array to be an empty array of the same length, and then += the value instead of setting it to the value.
public float[] PlaySineWave(float[] frequency, float amplitude, float[] data, int channels) { data = new float[data.Length]; for (int i = 0; i < frequency.Length; i++) { double phaseIncrement = frequency[i] / sampleRate; for (int sample = 0; sample < data.Length; sample += channels) { float value = Mathf.Sin((float)phase * 2 * Mathf.PI) * amplitude * saturation; phase = (phase + phaseIncrement) % 1; for (int chan = 0; chan < channels; chan++) { data[sample + chan] += value; } } } return data; }However, doing this seems to break OnAudioFilterRead(float[], int). I am able to debug this and see that the data variable is doing what it is supposed to do and its content is changing in OnAudioFilterRead(float[], int) as expected, but the method itself just ceases to function during runtime. Why does this happen? Does the data variable have some kind of reference that is wiped when overridden? As far as I know, the data variable is just a float array and I don't believe float arrays can have any references without some kind of keyword. What am I missing here?
