Voice Additive

by Ehsan Ziya

JavaScript

var context = new webkitAudioContext();
var gain = context.createGain();
gain.gain.value = 1;
gain.connect(context.destination);

function Voice(oscType, freq, oscNumber, pitchunison, panunison, attack, release) {
    var now = context.currentTime;
    this.release = release;
    var that = this;
    //VOICE GAIN
    var voicegain = context.createGain(); //create gain control for each voice
    voicegain.connect(gain); //destination

    var osc = context.createOscillator();
    osc.type = oscType;
    osc.connect(voicegain);
    osc.frequency.value = freq;
    osc.start(now);
    
    var moreThanOne = false; // if there is only 1 osc needed
    
    // if more than 1 oscillator    
    if (oscNumber > 1) {
        moreThanOne = true;
        for (var i = 0; i < oscNumber-1; i++) {
            var osc1 = context.createOscillator();
            osc1.type = oscType;
            var pan1 = context.createPanner(); // pan unison for each particle
            pan1.panningModel = "equalpower"; // defaults to hrtf
            // random pan level selection in the specified range between -1 and 1
            var panunisonval = ((Math.random() * panunison) - panunison / 2) * (panunison * 0.0001);
            
            pan1.setPosition(panunisonval,0,0);
            
            osc1.frequency.value = freq;
            //pitch unison random for each particle
            var detuneval = (Math.random() * pitchunison) - (pitchunison / 2);
            osc1.detune.value = detuneval;
            osc1.connect(pan1);
            pan1.connect(voicegain);
            osc1.start(now);


        }
    }
    //linear attack section
    voicegain.gain.setValueAtTime(0, now);
    voicegain.gain.linearRampToValueAtTime(1 / oscNumber * 2, now + attack);
    
    // noteOff method
    this.noteOff = function () {
        //release and deleting the created nodes
        voicegain.gain.linearRampToValueAtTime(0, now + that.release);
        osc.stop(now + that.release + 2);
       ...