Skip to content

Instantly share code, notes, and snippets.

@veltman
Last active August 12, 2016 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veltman/929490702f3c95e3260acf9696179d20 to your computer and use it in GitHub Desktop.
Save veltman/929490702f3c95e3260acf9696179d20 to your computer and use it in GitHub Desktop.
Looping pseudo-video w/ sound (sprite)
<!DOCTYPE html>
<meta charset="utf-8">
<style>
div {
width: 480px;,
height: 250px;
margin: 125px auto;
}
</style>
<body>
<div><canvas width="480" height="250"></canvas></div>
<script>
var context = document.querySelector("canvas").getContext("2d"),
audioContext = new (window.AudioContext || window.webkitAudioContext)();
var request = new XMLHttpRequest(),
image = new Image();
request.responseType = "arraybuffer";
request.open("GET", "llcoolj.wav", true);
// XHR complete
request.onload = function() {
audioContext.decodeAudioData(request.response, success, function(err){ throw err; });
};
image.onload = function() {
request.send();
}
image.src = "sprite.png";
function success(buffer) {
var source = audioContext.createBufferSource();
var gainNode = audioContext.createGain();
// Keep it quiet
gainNode.gain.value = 0.2;
source.connect(gainNode);
gainNode.connect(audioContext.destination);
// Set the buffer
source.buffer = buffer;
source.loop = true;
var secondsPerFrame = buffer.duration / 94,
t0 = audioContext.currentTime;
source.start(0);
requestAnimationFrame(update);
function update(){
var frame = Math.floor(((audioContext.currentTime - t0) % buffer.duration) / secondsPerFrame);
context.drawImage(image, 0, frame * 250, 480, 250, 0, 0, 480, 250);
requestAnimationFrame(update);
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment