Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $(function(){
- var $keyboard = $('.keyboard')
- , $buttons = $keyboard.find('button')
- , charMap = {}
- , keyList = []
- , char
- , audioCtx = new AudioContext()
- , oscMap = {};
- for(var i=0; i < $buttons.length; i++){
- char = $buttons[i].innerHTML;
- keyList.push(charMap[char] = {
- $button: $($buttons[i]),
- index:i,
- char:char,
- playing:false
- });
- }
- function getFreq(i){
- return 220 * Math.pow(2, (i+3)/12);
- }
- function playNote(obj, playing){
- if(obj && obj.playing != playing){
- obj.playing = playing;
- if(playing){
- if(!obj.osc){
- obj.osc = audioCtx.createOscillator();
- obj.osc.type = 'square';
- obj.osc.frequency.value = getFreq(obj.index);
- obj.osc.connect(audioCtx.destination);
- }
- obj.osc.start();
- } else {
- if(obj.osc){
- obj.osc.stop();
- obj.osc = null;
- }
- }
- obj.$button[playing ? 'addClass' : 'removeClass']('playing');
- }
- }
- $(window).on('keydown keyup', function(e){
- var c = e.originalEvent.key || '';
- playNote(charMap[c.toUpperCase()], e.type == 'keydown');
- });
- $keyboard.on('mousedown mouseup', 'button', function(e){
- var c = this.innerHTML;
- playNote(charMap[c.toUpperCase()], e.type == 'mousedown');
- })
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement