Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. $(function(){
  2.  
  3. var $keyboard = $('.keyboard')
  4. , $buttons = $keyboard.find('button')
  5. , charMap = {}
  6. , keyList = []
  7. , char
  8. , audioCtx = new AudioContext()
  9. , oscMap = {};
  10.  
  11. for(var i=0; i < $buttons.length; i++){
  12. char = $buttons[i].innerHTML;
  13. keyList.push(charMap[char] = {
  14. $button: $($buttons[i]),
  15. index:i,
  16. char:char,
  17. playing:false
  18. });
  19. }
  20.  
  21. function getFreq(i){
  22. return 220 * Math.pow(2, (i+3)/12);
  23. }
  24.  
  25. function playNote(obj, playing){
  26. if(obj && obj.playing != playing){
  27. obj.playing = playing;
  28. if(playing){
  29. if(!obj.osc){
  30. obj.osc = audioCtx.createOscillator();
  31. obj.osc.type = 'square';
  32. obj.osc.frequency.value = getFreq(obj.index);
  33. obj.osc.connect(audioCtx.destination);
  34.  
  35. }
  36. obj.osc.start();
  37. } else {
  38. if(obj.osc){
  39. obj.osc.stop();
  40. obj.osc = null;
  41. }
  42. }
  43. obj.$button[playing ? 'addClass' : 'removeClass']('playing');
  44. }
  45.  
  46. }
  47.  
  48. $(window).on('keydown keyup', function(e){
  49. var c = e.originalEvent.key || '';
  50. playNote(charMap[c.toUpperCase()], e.type == 'keydown');
  51. });
  52.  
  53. $keyboard.on('mousedown mouseup', 'button', function(e){
  54. var c = this.innerHTML;
  55. playNote(charMap[c.toUpperCase()], e.type == 'mousedown');
  56. })
  57.  
  58. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement