Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Created November 8, 2016 00:52
Show Gist options
  • Save mohayonao/b4f22bf75e8d9c16c5575174aa0c7ea9 to your computer and use it in GitHub Desktop.
Save mohayonao/b4f22bf75e8d9c16c5575174aa0c7ea9 to your computer and use it in GitHub Desktop.
function example01(audioContext, pulse) {
var destination = audioContext.destination;
var t0 = audioContext.currentTime;
pulse(destination, t0, { frequency: 440, volume: 0.3, duty: 0.8 });
}
function pulse(destination, playbackTime, opts) {
var t0 = playbackTime;
var audioContext = destination.context;
var oscillator = audioContext.createOscillator();
var waveShaper = audioContext.createWaveShaper();
var gain = audioContext.createGain();
var frequency = opts.frequency;
var volume = opts.volume;
var curve = new Float32Array(2048);
for (var i = 0; i < 2048; i++) {
curve[i] = (i / 2048) < 1 - opts.duty ? -1 : +1;
}
oscillator.type = "triangle";
oscillator.frequency.value = frequency;
oscillator.start(t0);
oscillator.connect(waveShaper);
waveShaper.curve = curve;
waveShaper.connect(gain);
gain.gain.value = volume;
gain.connect(destination);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment