Skip to content

Instantly share code, notes, and snippets.

@reimertz
Created June 9, 2016 13:25
Show Gist options
  • Save reimertz/a578fc24ac10ff2a2037e10154e47595 to your computer and use it in GitHub Desktop.
Save reimertz/a578fc24ac10ff2a2037e10154e47595 to your computer and use it in GitHub Desktop.
synth.js
//I created a quick suprise for you.
//Paste this on any homepage and you'll get a //surprise.. Also, it's less than 250 words!
document.body.innerHTML += '<div class="piano"></div>';
document.head.innerHTML += '<style>.piano{display:flex;flex-direction:row;justify-content:center;margin:50px;position:relative}.piano:before{width:100%;text-align:center;content:\'Because I created this\';position:absolute;display:block;left:0;top:-25px}.piano>*{width:50px;height:100px;background-color:wheat;border-right:1px solid #fff;opacity:.8}.piano>[class$="#"]{background:#000;position:absolute;height:50px;margin-left:-25px;z-index:1}.piano>:hover{opacity:.9}.piano>:active{opacity:1;transform:scaleY(.9);transform-origin:top center}</style>';
var p = document.querySelector('.piano'),
keyMap = {
'c': 65.41,
'c#': 69.30,
'd': 73.42,
'd#': 77.78,
'e': 82.41,
'f': 87.31,
'f#': 92.50,
'g': 98.00,
'g#': 103.8,
'a': 110.0,
'a#': 116.5,
'b': 123.5,
'c2': 130.81,
'c2#': 138.59,
'd2': 146.83,
'd2#': 155.56,
'e2': 164.81,
'f2': 174.61,
'f2#': 185.00,
'g2': 196.00,
'g2#': 207.65,
'a2': 220.00,
'a2#': 233.08,
'b2': 246.94,
},
ac = new (window.AudioContext || window.webkitAudioContext)(),
o = ac.createOscillator(),
gn = ac.createGain();
Object.keys(keyMap).map(function(key){
p.innerHTML = p.innerHTML + '<div class="' + key + '"></div>';
})
o.connect(gn); o.type = 'square'; o.frequency.value = 80; o.start(0);
gn.connect(ac.destination); gn.gain.value = 0;
t = false;
function playTone(f) {
o.frequency.value = f; // value in hertz
console.log(f + 396.19)
gn.gain.value = 0.5;
}
function stopeTone() {
gn.gain.value -= 0.01;
if(gn.gain.value > 0 ) {
clearTimeout(t);
t = setTimeout(stopeTone, 10)
}
}
document.querySelector('.piano').addEventListener('mousedown', function(e){
var tone = e.srcElement.classList[0];
playTone(keyMap[tone]);
});
document.querySelector('.piano').addEventListener('mouseup', function(e){
stopeTone()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment