Five Implementations of Saw Wave Oscillator

May 24, 2013 by aike
January 2, 2015 updated

oversampling ratio
highest harmonics limit current highest harmonics :30

Naive Logic

    this.phase += this.delta;
    if (this.phase > this.PI2) {
        this.phase -= this.PI2;
    }
    return 1.0 - (this.phase / Math.PI);

Oversampling

    var w = 0.0;
    var i;
    for (i = 0; i < this.oversampling; i++) {
        this.phase += this.delta / this.oversampling;
        if (this.phase > Math.PI * 2) {
            this.phase -= Math.PI * 2;
        }
        w += (1.0 - (this.phase / Math.PI)) / this.oversampling;
    }
    return w;

Additive Synthesis

    var out = 0.0;
    var n;
    for (n = 1; ; n++) {
        if (this.frequency * n > this.samplerate / 2)
            break;
        var overtone = Math.sin(this.phase * n) / n;
        out += overtone;
        if (n >= this.highestharmonics)
            break;
    }
    return out;

BLIT

    if (this.x >= 0.5) {
        this.x -= 1.0;
        this.p = this.samplerate / this.frequency;
        this.f = 1.0 / this.p;
        this.m = 2 * Math.floor(this.p / 2) + 1;
        this.sum = this.c3 = 0.0;
    }
    this.sum += this.m / this.p * Math.sin(this.m * this.x * Math.PI)
                / (this.m * Math.sin(this.x * Math.PI));
    this.x += this.f;
    this.c3 += this.f;
    return 2.0 * (this.sum - this.c3);

Oscillator Node

    this.onode = this.ctx.createOscillator();
    this.onode.type = "sawtooth";
    this.onode.connect(this.ctx.destination);
    this.onode.start(0);