Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Created August 29, 2016 04:31
Show Gist options
  • Select an option

  • Save mohayonao/6f7daddda053b975a705ce8437e434ce to your computer and use it in GitHub Desktop.

Select an option

Save mohayonao/6f7daddda053b975a705ce8437e434ce to your computer and use it in GitHub Desktop.
let audioContext = new AudioContext();
let sched = new WebAudioScheduler({
context: audioContext
});
function metronome(e) {
sched.insert(e.playbackTime + 0.000, ticktack, { frequency: 880, duration: 1.00 });
sched.insert(e.playbackTime + 0.500, ticktack, { frequency: 440, duration: 0.05 });
sched.insert(e.playbackTime + 1.000, ticktack, { frequency: 440, duration: 0.05 });
sched.insert(e.playbackTime + 1.500, ticktack, { frequency: 440, duration: 0.05 });
sched.insert(e.playbackTime + 2.000, metronome);
}
function ticktack(e) {
let t0 = e.playbackTime;
let t1 = t0 + e.args.duration;
let osc = audioContext.createOscillator();
let amp = audioContext.createGain();
osc.frequency.value = e.args.frequency;
osc.start(t0);
osc.stop(t1);
osc.connect(amp);
amp.gain.setValueAtTime(0.5, t0);
amp.gain.exponentialRampToValueAtTime(1e-6, t1);
amp.connect(masterGain); // <-- connect to master gain, instead of AudioDestinationNode
sched.nextTick(t1, () => {
osc.disconnect();
amp.disconnect();
});
}
function start() {
sched.start(metronome);
}
function stop() {
sched.stop(true);
}
let masterGain = null;
sched.on("start", () => {
masterGain = audioContext.createGain();
});
sched.on("stop", () => {
masterGain.disconnect();
masterGain = null;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment