Skip to content

Instantly share code, notes, and snippets.

@cfstras
Last active January 30, 2024 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cfstras/c42b8ed9a5e0f3d4d4438f2cf95f5c08 to your computer and use it in GitHub Desktop.
Save cfstras/c42b8ed9a5e0f3d4d4438f2cf95f5c08 to your computer and use it in GitHub Desktop.
Shepard tone with muzikilo.js
// https://github.com/anuejn/muzikilo.js
const {sin, PI, round, pow, abs, floor, exp} = Math
this.t += 1/44100
const sine = (name, f) => {
let phi = this[name] += 1/44100 * 2 * PI * f * saw(name+10000,f*0.5)
this[name] %= 2*PI
return sin(phi)
}
const saw = (name, f) => {
let phi = this[name] += 1/44100 * f
this[name] %= 1
return phi
}
const len = 40 * knobs.seconds + 1
const octaves = 4 * knobs.octaves
const minFreq = knobs.minFreq * 440
const tones = Math.floor(9 * knobs.tones) + 1
const tone = (name, t) => {
let freq = minFreq + (t % len) / len * 440*octaves
// downwards:
//freq = minFreq + 440 * octaves - freq
let vol = abs(((t-len/2) % len) / len - 0.5)
vol = pow(vol, 3)
//return saw(name, freq) * vol
return sine(name, freq) * vol
}
let v = 0;
for (let i = 0; i < tones; i+=1) {
let off = len / tones * i
v += tone(i, this.t+off)
}
return v * 2 * knobs.volume
@anuejn
Copy link

anuejn commented Jun 3, 2018

Nice :)

@rillig
Copy link

rillig commented Oct 31, 2018

One possible performance enhancement is to replace this[name] with this[number]. Adding two numbers is much faster than concatenating two strings, plus it doesn't overload the garbage collector.

const Sine = 0
const Saw = 1
const Tone = 2
function name(type, index) {
    return 16 * index + type
}

// And then:
this[name(Sine, 14)] = 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment