subpoly
Version:
a Web Audio subtractive, polyphonic synthesizer
98 lines (80 loc) • 2.73 kB
JavaScript
// npm support
if (typeof require !== 'undefined') {
var Monosynth = require('submono');
}
var Polysynth = function Polysynth(audioCtx, config) {
var synth;
var Synth = function Synth() {
synth = this;
synth.audioCtx = audioCtx;
synth.voices = [];
config = config || {};
config.cutoff = config.cutoff || {};
for (var i = 0, ii = config.numVoices || 16; i < ii; i++) {
synth.voices.push(new Monosynth(audioCtx, config));
}
synth.stereoWidth = config.stereoWidth || 0.5; // out of 1
synth.width(synth.stereoWidth);
return synth;
};
// apply attack, decay, sustain envelope
Synth.prototype.start = function startSynth() {
synth.voices.forEach(function startVoice(voice) {
voice.start();
});
};
// apply release envelope
Synth.prototype.stop = function stopSynth() {
synth.voices.forEach(function stopVoice(voice) {
voice.stop();
});
};
// get/set synth stereo width
Synth.prototype.width = function width(newWidth) {
if (synth.voices.length > 1 && newWidth) {
synth.stereoWidth = newWidth;
synth.voices.forEach(function panVoice(voice, i) {
var spread = 1/(synth.voices.length - 1);
var xPos = spread * i * synth.stereoWidth;
var zPos = 1 - Math.abs(xPos);
voice.pan.setPosition(xPos, 0, zPos);
});
}
return synth.stereoWidth;
};
// convenience methods for changing values of all Monosynths' properties at once
(function createSetters() {
var monosynthProperties = ['maxGain', 'attack', 'decay', 'sustain', 'release'];
var monosynthCutoffProperties = ['maxFrequency', 'attack', 'decay', 'sustain'];
monosynthProperties.forEach(function createSetter(property) {
Synth.prototype[property] = function setValues(newValue) {
synth.voices.forEach(function setValue(voice) {
voice[property] = newValue;
});
};
});
Synth.prototype.cutoff = {};
monosynthCutoffProperties.forEach(function createSetter(property) {
Synth.prototype.cutoff[property] = function setValues(newValue) {
synth.voices.forEach(function setValue(voice) {
voice.cutoff[property] = newValue;
});
};
});
Synth.prototype.waveform = function waveform(newWaveform) {
synth.voices.forEach(function waveform(voice) {
voice.waveform(newWaveform);
});
};
Synth.prototype.pitch = function pitch(newPitch) {
synth.voices.forEach(function pitch(voice) {
voice.pitch(newPitch);
});
};
})();
return new Synth;
};
// npm support
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = Polysynth;
}