Skip to content

Instantly share code, notes, and snippets.

@aybe
Forked from MattRix/BitCrusher.cs
Created October 16, 2016 16:34
Show Gist options
  • Save aybe/c6c990c20f8d8759307c310baef44df5 to your computer and use it in GitHub Desktop.
Save aybe/c6c990c20f8d8759307c310baef44df5 to your computer and use it in GitHub Desktop.

Revisions

  1. @MattRix MattRix created this gist Sep 15, 2014.
    37 changes: 37 additions & 0 deletions BitCrusher.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    public class BitCrusher : MonoBehaviour
    {
    [Range (1f,16f)]
    public float bits = 16f;

    [Range (20f,48000f)]
    public float sampleRate = 48000f;

    private float phase = 0;
    private float last = 0;
    private float baseSampleRate;

    public BitCrusher()
    {
    baseSampleRate = (float)AudioSettings.outputSampleRate;
    }

    public void OnAudioFilterRead(float[] data, int channels)
    {
    float freqDelta = sampleRate/baseSampleRate;
    float quantizeReso = Mathf.Pow(2f,bits);

    int length = data.Length;
    for(int d = 0; d<length; d++)
    {
    phase = phase + freqDelta;
    if(phase >= 1f)
    {
    phase = phase - 1f;
    last = Mathf.Floor((data[d]*quantizeReso) + 0.5f) / quantizeReso;
    }

    data[d] = last;
    data[++d] = last;
    }
    }
    }