Search Unity

Create Sine Wave Envelope in OnAudioFilterRead

Discussion in 'Scripting' started by syhrmr, Feb 21, 2018.

  1. syhrmr

    syhrmr

    Joined:
    Feb 21, 2018
    Posts:
    10
    Hi all, I'm trying to make a sine wave in OnAudioFilterRead() method to generate it using an equation a = sin((2 * phi * frequency * sample length) / sampling rate). But I have two problem with this,

    1. How to limit the sine wave length and assign it to sample length?
    2. How to implement an envelope so I can create a waveform with attack, decay, sustain, and release?

    Below is simple code that I've implemented.

    private void OnAudioFilterRead (float[] data, int channels) {
    Code (CSharp):
    1. private void OnAudioFilterRead (float[] data, int channels) {
    2.         increment = (frequency * 2.0 * Mathf.PI ) / samplingFq;
    3.        
    4.         for (int i = 0; i < data.Length; i += channels) {
    5.             phase         += increment;
    6.             data[i]     = phase;
    7.  
    8.             if (channels == 2)                data[i + 1] = data[i];
    9.             if (phase > (Mathf.PI * 2))        phase         = 0.0;
    10.         }
    11.        
    12.     }
    Thank you.
     
    april_4_short likes this.
  2. syhrmr

    syhrmr

    Joined:
    Feb 21, 2018
    Posts:
    10
    Anyone can help?
     
  3. april_4_short

    april_4_short

    Joined:
    Jul 19, 2021
    Posts:
    489
    Have same questions. Did you ever figure this out?