Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Created November 8, 2016 02:23
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 mohayonao/24c74758413ee55e2876857d1ead36d5 to your computer and use it in GitHub Desktop.
Save mohayonao/24c74758413ee55e2876857d1ead36d5 to your computer and use it in GitHub Desktop.
function pulse(destination, playbackTime, opts) {
var t0 = playbackTime;
var audioContext = destination.context;
var oscillator = audioContext.createOscillator();
var gain = audioContext.createGain();
var frequency = opts.frequency;
var volume = opts.volume;
function createPulseWave(audioContext, duty, length) {
var a = new Float32Array(length);
var b = new Float32Array(length);
for (var i = 1; i < length; i++) {
a[i] = (2 / (i * Math.PI)) * Math.sin(duty * i * Math.PI);
}
return audioContext.createPeriodicWave(a, b);
}
var wave = createPulseWave(audioContext, opts.duty, 2048);
oscillator.setPeriodicWave(wave);
oscillator.frequency.value = frequency;
oscillator.start(t0);
oscillator.connect(gain);
gain.gain.value = volume;
gain.connect(destination);
}
function example01(audioContext, pulse) {
function mtof(midi) {
return 440 * Math.pow(2, (midi - 69) / 12);
}
var destination = audioContext.destination;
var t0 = audioContext.currentTime;
pulse(destination, t0, { frequency: 440, volume: 0.4, duty: 0.9 });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment