Last active
June 20, 2017 14:10
-
-
Save jakubfiala/1576b8e76eedd96f896d171122845ac3 to your computer and use it in GitHub Desktop.
A simple Web Audio sequencer function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// creates a Sequence for the given AudioContext, which changes the `param` of the `node` according to a specified `seq` array with a given `smoothness` | |
// Example of a `seq` array: | |
// [ [0, 440], [1, 220], [1.5, 330], [2, 440] ] | |
// English: set the value to 440 immediately, then to 220 after 1 second, then to 330 after 1.5 seconds, then return to 440 after 2 seconds | |
// | |
// returns an object containing 3 methods: | |
// | |
// - `playOnce` will perform the sequence once | |
// - `loop` will loop the sequence indefinitely | |
// - `stop` will stop looping the sequence | |
// | |
// Example usage: | |
// | |
// let mySequence = sequence( | |
// context, | |
// oscillator, | |
// 'frequency', | |
// [ [0, 440], [1, 220], [1.5, 330], [2, 440] ], | |
// 0.2 | |
// ); | |
// | |
const sequence = (ctx, node, param, seq, smoothness) => { | |
const duration = seq.reduce((acc, it) => acc + it[0], 0); | |
let on = true; | |
const control = { | |
playOnce: () => { | |
for (let point of seq) { | |
if (smoothness) { | |
node[param].setTargetAtTime(point[1], ctx.currentTime + point[0], smoothness); | |
} | |
else { | |
node[param].setValueAtTime(point[1], ctx.currentTime + point[0]); | |
} | |
}; | |
}, | |
loop: function() { | |
on = true; | |
node[param].cancelScheduledValues(ctx.currentTime); | |
const repeat = () => { | |
this.playOnce(); | |
if (on) this._timeout = setTimeout(repeat, duration * 1000); | |
}; | |
this._timeout = setTimeout(repeat, duration * 1000); | |
}, | |
stop: () => { | |
clearTimeout(this._timeout); | |
node[param].cancelScheduledValues(ctx.currentTime); | |
on = false; | |
} | |
} | |
return control; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment