Skip to content

Instantly share code, notes, and snippets.

@tkojitu
Last active August 29, 2015 14:01
Show Gist options
  • Save tkojitu/074b4afe240704d7590b to your computer and use it in GitHub Desktop.
Save tkojitu/074b4afe240704d7590b to your computer and use it in GitHub Desktop.
touch it then shake it.
<html>
<head>
<style>
#viewport {
border: 1px solid #000000;
}
</style>
<script src="gbend.js"></script>
</head>
<body>
<canvas id="viewport" width=300 height=300></canvas>
</body>
</html>
var gContext;
var gOscillator;
function onLoad() {
gContext = new webkitAudioContext();
addEventListeners();
}
function addEventListeners() {
var view = document.getElementById("viewport");
view.addEventListener("touchstart", onTouchStart, false);
view.addEventListener("touchend", onTouchEnd, false);
window.addEventListener("devicemotion", onDeviceMotion, false);
}
function onTouchStart(event) {
event.preventDefault();
var gain = gContext.createGainNode();
gain.gain.value = 0.5;
gain.connect(gContext.destination);
gOscillator = gContext.createOscillator();
gOscillator.type = "square";
gOscillator.frequency.value = 440.0;
gOscillator.connect(gain);
gOscillator.start(0);
}
function onTouchEnd(event) {
event.preventDefault();
gOscillator.stop(0);
gOscillator = null;
}
function onDeviceMotion(event) {
event.preventDefault();
var acc = event.accelerationIncludingGravity;
if (gOscillator === null) {
return;
}
var v = Math.sqrt(acc.x * acc.x + acc.y * acc.y + acc.z * acc.z);
gOscillator.frequency.value = 440.0 + (v - 9.81) * 2;
}
window.addEventListener("load", onLoad, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment