Created
December 18, 2012 07:52
-
-
Save epicure/4325939 to your computer and use it in GitHub Desktop.
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
var gWave, gFreq, ac, osc, osc1, gainNode, analyser, buffWave, buffFreq; | |
var update = function() { | |
var i, x; | |
gWave.clearRect(0, 0, gWave.canvas.width, gWave.canvas.height); | |
gFreq.clearRect(0, 0, gFreq.canvas.width, gFreq.canvas.height); | |
analyser.getByteTimeDomainData(buffWave); | |
analyser.getByteFrequencyData(buffFreq); | |
for(i = 0; i < buffWave.length; i++) { | |
x = i / (buffWave.length - 1) * gWave.canvas.width; | |
gWave.beginPath(); | |
gWave.moveTo(x, gWave.canvas.height * 0.5); | |
gWave.lineTo(x, gWave.canvas.height * 0.5 + (buffWave[i] - 127) / 255 * gWave.canvas.height); | |
gWave.stroke(); | |
} | |
for(i = 0; i < buffFreq.length; i++) { | |
x = i / (buffFreq.length - 1) * gFreq.canvas.width; | |
gFreq.beginPath(); | |
gFreq.moveTo(x, gFreq.canvas.height); | |
gFreq.lineTo(x, gFreq.canvas.height - buffFreq[i] / 255 * gFreq.canvas.height); | |
gFreq.stroke(); | |
} | |
}; | |
var loop = function() { | |
update(); | |
webkitRequestAnimationFrame(loop); | |
}; | |
var init = function() { | |
gWave = document.querySelector('#wave').getContext('2d'); | |
gWave.canvas.width = 200; | |
gWave.canvas.height = 100; | |
gFreq = document.querySelector('#freq').getContext('2d'); | |
gFreq.canvas.width = 200; | |
gFreq.canvas.height = 100; | |
ac = new webkitAudioContext(); | |
osc = ac.createOscillator(); | |
osc1 = ac.createOscillator(); | |
gainNode = ac.createGainNode(); | |
analyser = ac.createAnalyser(); | |
osc.connect(gainNode); | |
//osc1.connect(gainNode); | |
gainNode.connect(analyser); | |
analyser.connect(ac.destination); | |
buffWave = new Uint8Array(analyser.frequencyBinCount); | |
buffFreq = new Uint8Array(analyser.fftSize); | |
osc.noteOn(0); | |
osc1.noteOn(0); | |
loop(); | |
}; | |
window.onload = function(e) { | |
init(); | |
}; | |
window.onkeydown = function(e) { | |
console.log(e.keyCode); | |
var freq = 0; | |
switch(e.keyCode) { | |
case 65: | |
freq = Math.pow(2, 3 / 12) * 440; | |
break; | |
case 83: | |
freq = Math.pow(2, 5 / 12) * 440; | |
break; | |
case 68: | |
freq = Math.pow(2, 7 / 12) * 440; | |
break; | |
} | |
osc.frequency.value = freq; | |
//osc1.frequency.value = freq + 10; | |
gainNode.gain.setValueAtTime(0, ac.currentTime); | |
gainNode.gain.linearRampToValueAtTime(1, ac.currentTime + 0.2); | |
gainNode.gain.linearRampToValueAtTime(0.8, ac.currentTime + 0.4); | |
gainNode.gain.linearRampToValueAtTime(0.7, ac.currentTime + 0.6); | |
gainNode.gain.linearRampToValueAtTime(0, ac.currentTime + 1.0); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment