Realtime Procedural Audio and Synthesized Piano in Unity 3D

An introduction to mathematically generate the sound waveforms and create any sound you wish with endless variations

How Does The Speaker Generate Sounds

Programming The Speaker Cone

Speaker Cone Displacement = sin(time* 2π *frequency)
Or
float waveFunction(time, frequency)
{
return sin(time* 2π *frequency);
}

Implementation Details in Unity

for(int i = 0; i<data[].length; i = i +2) 
{
data[i] = waveFunction(currentThreadTime + i/sampleRate, freque)
data[i+1] = data[i];
}
for(int i = 0; i<data[].length; i = i + channels) 
{
data[i] = waveFunction(currentThreadTime + i/sampleRate, freque)
for(int j = 1; j<channels; j++)
{
data[i+j] = data[i];
}
}
float increment = (frequency * 2π) / sampleRate
for(int i = 0; i<data[].length; i = i + channels)
{
phase += increment;
if(phase>2π) phase = 0;
data[i] = sin(phase)
for(int j = 1; j<channels; j++)
{
data[i+j] = data[i];
}
}

Modulo as Alternative

phase =(float)(totalTime %(1.0/(double)frequency)) * frequency * 2π;
phase =(float)(totalTime %(1.0/(double)frequency));
phase = (phase + i/sampleRate) * frequency * 2π;
data[i] = Mathf.Sin(phase);

Creating Musical Notes

data[i] = waveFunction(time, fundementalFrequency       ) +
waveFunction(time, fundementalFrequency * 2.0f);
Notice how while AD and R are duration S is a measure of volume/ loudness

Final Thoughts

Further Improvements

Further Reading

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store