Web Audio Basics (Concise)
by Aqilah Misuary
HTML
<button id="playSoundBtn">Play</button>
<button id="stopSoundBtn">Stop</button>
JavaScript
var context = new (window.AudioContext || window.webkitAudioContext)();
var source;
var songLength;
var url = "https://dl.dropboxusercontent.com/u/30075450/Always%20In%20My%20Head%20-%20Coldplay.mp3";
var myAudioBuffer;
var play = document.getElementById("playSoundBtn");
var stop = document.getElementById("stopSoundBtn");
function getAudioData() {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function () {
context.decodeAudioData(request.response, function (buffer) {
myAudioBuffer = buffer;
source = context.createBufferSource();
source.buffer = myAudioBuffer;
source.start(0);
source.connect(context.destination);
});
}
request.send();
}
play.onclick = function() {
getAudioData();
play.setAttribute('disabled', 'disabled');
}
stop.onclick = function() {
source.stop(0);
play.removeAttribute('disabled');
}