Over a million developers have joined DZone.

Inception Score Easter Egg with Web Audio API

DZone 's Guide to

Inception Score Easter Egg with Web Audio API

· Web Dev Zone ·
Free Resource

There's a great video on YouTube detailing an Easter Egg in the score for the movie Inception.  Basically Inception is about dreams and the slowing down of time. Likewise the score is based on the slowing down of music that is played inside the plot of the movie.  Pretty cool. Feel free to check out the video before continuing.

I wanted to use this concept to show off the Audio capabilities in HTML5. Basically I want to:

  • Play the Inception Score
  • Play the Edith Piaf song
  • Play the Edit Piaf song slowed down
  • Play the Inception score over the slowed down Edith Piaf song.

But the vanilla tag didn't work for me. The tag does have the ability to be slowed down, but it seems that in Chrome and Safari, I could not get the rate below 50% of the original. On Chrome the sound stopped playing if the rate was below 50%, and on Safari the sound just never got slower even though the rate was below 50%.

I figured I would give the Web Audio API a try and see what it could do. So I wrote a function that could play back a sound at a given rate:

function playAudio(file, speed){	
	if (typeof AudioContext == "function") {
		var audioContext = new AudioContext();
	} else if (typeof webkitAudioContext == "function") {
		var audioContext = new webkitAudioContext();

	var source = audioContext.createBufferSource();

	var xhr = new XMLHttpRequest();
	xhr.open("GET", file, true);
	xhr.responseType = "arraybuffer";
	xhr.onload = function() {
		var buffer = audioContext.createBuffer(xhr.response, false);
		source.buffer = buffer;
		source.playbackRate.value = speed;

That worked. All I had to do was set up some HTML to display it, some CSS to make it look less plain, and some buttons to make it work.

There's a working demo here:

Audio API Demo

Oh before you click on that link - It only works on Chrome. And sometimes it has the tendency to stop working all together. The fix is to empty your browser cache, and restart Chrome. But hey, still a cool proof of concept.


Source: http://www.terrenceryan.com/blog/post.cfm/inception-score-easter-egg-with-web-audio-api



Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}