Skip to content

Example oscillators

Claus F. Strasburger edited this page Aug 25, 2020 · 11 revisions

All oscillators keep their own time, so they're independent of this.t. You need to call them with a name to keep the timers apart, and a frequency f.

Sine wave

const sine = (name, f) => {
    return Math.sin(this["sine_" + name] += 1/44100 * 2 * Math.PI * f) 
}

Saw wave

const saw = (name, f) => {
    return this["saw_" + name] = (this["saw_" + name] + 1/44100 * f) % 1
}

Square wave

const square = (name, f) => {
    var v = (this["square_" +  name] = this["square_" + name] + 1/44100 * f) % 1
    return v > 0.5 ? 1 : 0
}

Sine modulated with detuned (octave lower) saw

const crunch = (name, f) => {
    name = "crunch_" + name;
    return Math.sin(this[name] += 1/44100 * 2 * Math.PI * f * saw(name, f * 0.508)) 
}

8-bit-like sine and saw

const chip_x = (osc, name, f) => {
    return Math.floor((osc(name, f) * 5)) / 5
}

const chip_sine = chip_x.bind(this, sine)
const chip_saw = chip_x.bind(this, saw)

Example usage:

const base = 200;
return (
    + 0.4 * sine("1", base)
    + 0.4 * sine("2", base * 5/4)
    + 0.4 * saw("1", base * 3/2)
    + 0.3 * square("1", base * 3/2)
    + 0.3 * crunch("1", base/2) 
)
Clone this wiki locally