Skip to content

Instantly share code, notes, and snippets.

@icidasset
Created July 8, 2012 11:36
Show Gist options
  • Save icidasset/3070611 to your computer and use it in GitHub Desktop.
Save icidasset/3070611 to your computer and use it in GitHub Desktop.
Web Audio API guide

Web Audio API Guide

Where to start, what to use, what to do, etc.

Audio Context

The main object for the API.

var AC = new webkitAudioContext();

Loading a sound

Loading a buffer via a XMLHttpRequest.

// previously defined: AC
var buffer, url, request, error_handler;

url = "music.mp3";
request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";

// decode asynchronously
request.onload = function() {
  AC.decodeAudioData(request.response, function(b) {
    buffer = b;
  }, error_handler);
}

// send request
request.send();

Playing a sound

To play the sound we need to create a 'source' for the sound.

// previously defined: AC, buffer
var source;

source = AC.createBufferSource();
source.buffer = buffer;
source.connect(AC.destination); // connect to the speakers
source.noteOn(0); // play

Playing a sound via an audio element

Why? Well, because it allows streaming

// previously defined: AC
var audio_element, source;

audio_element = new Audio();
audio_element.src = "music.mp3";
audio_element.autoplay = true;
document.body.appendChild(audio_element);

window.addEventListener("load", function(e) {
  source = AC.createMediaElementSource(audio_element);
  source.connect(AC.destination);
}, false);

Creating a gain node

// previously defined: AC, source
var volume_node;

volume_node = AC.createGainNode();
volume_node.gain.value = 0.5; // the volume

source.connect(volume_node);
volume_node.connect(AC.destination);

Creating a sound filter

// previously defined: AC, source, volume_node
var filter_node;

filter_node = AC.createBiquadFilter();
filter_node.type = 0; // low-pass filter
filter_node.frequency.value = 220;

source.connect(volume_node);
volume_node.connect(filter_node);
filter_node.connect(AC.destination);
http://www.youtube.com/watch?v=hFsCG7v9Y4c
https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
http://www.w3.org/wiki/HTML/Elements/audio#Media_Events
http://creativejs.com/resources/web-audio-api-getting-started/
http://www.html5rocks.com/en/tutorials/webaudio/intro/
http://updates.html5rocks.com/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs
http://updates.html5rocks.com/2012/01/Web-Audio-FAQ
http://www.lynda.com/tutorial/86649?utm_source=youtube&utm_medium=viral&utm_content=youtube&utm_campaign=youtube
http://jcla1.com/demos/web-audio-api/web-audio-overview-part2.html
http://html5-demos.appspot.com/static/webaudio/createMediaSourceElement.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment