1 tQuery.registerStatic('MidiKeyTween', function(opts){ 2 opts = this._opts = tQuery.extend(opts, { 3 attackTime : 2, 4 releaseTime : 2 5 }); 6 7 this._lastStart = Date.now()/1000 - (opts.attackTime + opts.releaseTime); 8 this._lastStop = Date.now()/1000 - (opts.attackTime + opts.releaseTime); 9 }); 10 11 12 tQuery.MidiKeyTween.prototype.press = function(){ 13 // if already press, do nothing 14 var state = this.state(); 15 if( state === 'attacking' ) return; 16 if( state === 'playing' ) return; 17 // update this._lastStart 18 this._lastStart = Date.now()/1000; 19 }; 20 21 tQuery.MidiKeyTween.prototype.release = function(){ 22 // if already release, do nothing 23 var state = this.state(); 24 if( state === 'releasing' ) return; 25 if( state === 'silent' ) return; 26 // update this._lastStop 27 this._lastStop = Date.now()/1000; 28 }; 29 30 tQuery.MidiKeyTween.prototype.value = function(){ 31 var now = Date.now()/1000; 32 var opts = this._opts; 33 if( this._lastStart <= this._lastStop ){ 34 if( now - this._lastStop < opts.releaseTime ){ 35 return (now - this._lastStop) / opts.releaseTime; 36 }else{ 37 return 0; 38 } 39 }else{ 40 console.assert( this._lastStart > this._lastStop ); 41 if( now - this._lastStart < opts.attackTime ){ 42 return (now - this._lastStart) / opts.attackTime; 43 }else{ 44 return 1; 45 } 46 } 47 }; 48 49 tQuery.MidiKeyTween.prototype.state = function(){ 50 var now = Date.now()/1000; 51 var opts = this._opts; 52 53 if( this._lastStart > this._lastStop ){ 54 console.assert( this._lastStart > this._lastStop ); 55 if( now - this._lastStart < opts.attackTime ){ 56 return 'attacking'; 57 }else{ 58 return 'playing'; 59 } 60 }else{ 61 if( now - this._lastStop < opts.releaseTime ){ 62 return 'releasing'; 63 }else{ 64 return 'silent'; 65 } 66 } 67 }; 68 69 70