Web Audio API Reverse Buffer

by Aqilah Misuary

HTML

<p>Web audio API example: load a sound file, reverse it and play/stop it on a button click.</p>
  <button onclick="initcontext()">Init</button>
  <button onclick="loadSound(url)">Load</button>
  <button onclick="playSound()">Play</button>
  <button onclick="stopSound()">Stop</button>

JavaScript

var context;
var url = "https://dl.dropboxusercontent.com/u/30075450/Always%20In%20My%20Head%20-%20Coldplay.mp3";
var source = null;
var myAudioBuffer = null;

function initcontext() {
    try {
        context = new AudioContext();
    } catch (e) {
        alert('Sorry, your browser does not support the Web Audio API.');
    }
}

function loadSound(url) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';
    request.onload = function () {
        context.decodeAudioData(request.response, function (buffer) {
            myAudioBuffer = buffer;
            playSound(myAudioBuffer);
        });
    }
    request.send();
}

function playSound(myAudioBuffer) {
    source = context.createBufferSource();
    source.buffer = myAudioBuffer;
		Array.prototype.reverse.call( myAudioBuffer.getChannelData(0) );
    Array.prototype.reverse.call( myAudioBuffer.getChannelData(1) );
    source.connect(context.destination);
    source.start();
}

function stopSound() {
    if (source) {
        source.stop();
    }
}