Skip to content

Instantly share code, notes, and snippets.

@rectalogic
Last active December 11, 2015 22:18
Show Gist options
  • Save rectalogic/4668580 to your computer and use it in GitHub Desktop.
Save rectalogic/4668580 to your computer and use it in GitHub Desktop.
Play a video on iPhone, toggle between playing and pausing when device is shaken.
<html>
<head>
<script type="text/javascript">
if (typeof window.DeviceMotionEvent != 'undefined') {
// Shake sensitivity (a lower number is more)
var sensitivity = 20;
// Position variables
var x1 = 0, y1 = 0, z1 = 0, x2 = 0, y2 = 0, z2 = 0;
// Listen to motion events and update the position
window.addEventListener('devicemotion', function (e) {
x1 = e.accelerationIncludingGravity.x;
y1 = e.accelerationIncludingGravity.y;
z1 = e.accelerationIncludingGravity.z;
}, false);
// Periodically check the position and fire
// if the change is greater than the sensitivity
setInterval(function () {
var change = Math.abs(x1-x2+y1-y2+z1-z2);
if (change > sensitivity) {
onShake();
}
// Update new position
x2 = x1;
y2 = y1;
z2 = z1;
}, 150);
}
function onShake() {
var video = document.getElementById("video");
video.paused ? video.play() : video.pause();
}
</script>
</head>
<body>
<video id="video" width="848" height="352" autoplay controls src="http://movies.apple.com/media/us/html5/showcase/2011/demos/apple-html5-demo-tron-us_848x352.m4v"></video>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment