#MonthOfCode - Day 13: sound

My entry for the 13th day of the month of code. The theme for today is: sound.

This is the most basic example of the WebAudio API. It plays a sound loaded via XHR.

Play sound

Code after the break.

sound.jsview raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
(function() {

var context;
if (typeof AudioContext !== "undefined") {
context = new AudioContext();
} else if (typeof webkitAudioContext !== "undefined") {
context = new webkitAudioContext();
} else {
throw new Error('AudioContext not supported. :(');
}

function play() {
var xhr = new XMLHttpRequest();
// creative commons source: https://www.freesound.org/people/Luftrum/sounds/58859/
xhr.open("GET", '/projects/monthofcode/13/rain.mp3', true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var data = xhr.response;
var source = context.createBufferSource();

source.buffer = context.createBuffer(data, true);

// connect source to output
source.connect(context.destination);

source.start(0);
};
xhr.send();
}

document.getElementById('moc-13').addEventListener('click', play, false);
}());