JSFiddle - React, Tailwind, and code Playground

by Aqilah Misuary

HTML

<h1>Sound Effects Demo</h1>
<form>
<input type='button' id='play1' value='play once'/>
<input type='button' id='play2' value='play staggered'/>

JavaScript

var ctx; //audio context
var buf; //audio buffer
var url = "https://dl.dropboxusercontent.com/u/30075450/Rays.wav";

//init the sound system
function init() {
    console.log("in init");
    try {
        ctx = new AudioContext(); 
        loadFile();
    } catch(e) {
        alert('you need webaudio support');
    }
}
window.addEventListener('load',init,false);

//load and decode mp3 file
function loadFile() {
    var req = new XMLHttpRequest();
    req.open("GET",url,true);
    req.responseType = "arraybuffer";
    req.onload = function() {
        //decode the loaded data
        ctx.decodeAudioData(req.response, function(buffer) {
            buf = buffer;
            setupButtons();
        });
    };
    req.send();
}

//play the loaded file
function play() {
    //create a source node from the buffer
    var src = ctx.createBufferSource(); 
    src.buffer = buf;
    //connect to the final output node (the speakers)
    src.connect(ctx.destination);
    //play immediately
    src.noteOn(0);
}

function setupButtons() {
    document.getElementById('play1').onclick = function() {
        play();
    }
    document.getElementById('play2').onclick = function() {
        var time = ctx.currentTime;
        for(var i=0; i<4; i++) {
            var src = ctx.createBufferSource(); 
            src.buffer = buf;
            //connect to the final output node (the speakers)
            src.connect(ctx.destination);
            //play immediately
            src.noteOn(time+i/4);
        }
    }
}