Criando um teclado com WebAudioAPI
<html> <body> <script> function onKeyDown(key){console.log(key)} function onKeyUp(key){console.log(key)} window.onkeydown = onKeyDown window.onkeyup = onKeyUp </script> </body> </html>
<html> <body> <script> const notes = { 'C3': 130.81, 'C#3': 138.59, 'D3': 146.83, 'D#3': 155.56, 'E3': 164.81, 'F3': 174.61, 'F#3': 185.00, 'G3': 196.00, 'G#3': 207.65, 'A3': 220.00, 'A#3': 233.08, 'B3': 246.94, 'C4': 261.63, 'C#4': 277.18, 'D4': 293.66, 'D#4': 311.13, 'E4': 329.63, 'F4': 349.23, 'F#4': 369.99, 'G4': 392.00, 'G#4': 415.30, 'A4': 440.00, 'A#4': 466.16, 'B4': 493.88, 'C5': 523.25, 'C#5': 554.37, 'D5': 587.33, 'D#5': 622.25, 'E5': 659.25, 'F5': 698.46, 'F#5': 739.99, 'G5': 783.99, 'G#5': 830.61, 'A5': 880.00, 'A#5': 932.33, 'B5': 987.77 } const map = { 65 = 'C3', 83 = 'D3', 68 = 'E3', 70 = 'F3', 71 = 'G3', 72 = 'A3', 74 = 'B3' } const context = new (window.AudioContext || window.webkitAudioContext)() function onKeyDown(key){ if(key.keyCode in map){ const osc = constext.createOscillator() osc.type = 'sine' osc.frequency.value = notes[map[key.keyCode]] osc.connect(contexto.destination) osc.start() osc.stop(contexto.currentTime+2) } } function onKeyUp(key){ console.log(key) } window.onkeydown = onKeyDown window.onkeyup = onKeyUp </script> </body> </html>
const mapOsc = {} function onKeyDown(key) { if (map[key.keyCode] && !mapOsc[key.keyCode]) { const osc = constext.createOscillator() osc.type = 'sine' osc.frequency.value = notes[map[key.keyCode]] osc.connect(contexto.destination) osc.start() mapOsc[key.keyCode] = osc } } function onKeyUp(key) { if (key.keyCode in mapOsc) { const osc = mapOsc[key.keyCode] osc.stop(0) mapOsc[key.keyCode] = undefined } }