Voice 2

by Ehsan Ziya

HTML

<script src="http://blog.chrislowis.co.uk/demos/polyphonic_synthesis/demo2/qwerty-hancock.js"></script>
<div id='keyboard'></div>

JavaScript

var context = new webkitAudioContext();
var activeVoices = [];

function voice(frequency,attack,release) {
    
    this.freq = frequency;
    this.osc = context.createOscillator();
    this.osc.frequency.value = frequency;
    this.gain = context.createGain();
    this.release = release;
    
    var that = this;
    var now = context.currentTime;
    
    this.osc.connect(this.gain);
    this.gain.connect(context.destination);
    
    this.gain.gain.setValueAtTime(0.0, now);
    this.gain.gain.linearRampToValueAtTime(1, now + attack);
    
    this.osc.start(now);
}

voice.prototype.off = function () {
    var now = context.currentTime;
    this.gain.gain.cancelScheduledValues(now);
    this.gain.gain.setValueAtTime( this.gain.gain.value, now );
    this.gain.gain.linearRampToValueAtTime(0.0, now + 1);
    this.osc.stop(now + 2);
};

var keyboard = qwertyHancock({
    id: 'keyboard',
    width: 600,
    height: 150,
    octaves: 3,
    startNote: 'A3',
    whiteNotesColour: 'white',
    blackNotesColour: 'black',
    hoverColour: '#f3e939',
    keyboardLayout: 'en'
});

keyboard.keyDown(function (note, frequency) {

    var v = new voice(frequency,1,1);
    activeVoices.push(v);
    

});

keyboard.keyUp(function (note, frequency) {
    
    for (var i = 0; i < activeVoices.length; i++) {
        
        if (Math.round(activeVoices[i].freq) === Math.round(frequency)) {
            activeVoices[i].off();
        }
    }
});