JSFiddle - React, Tailwind, and code Playground

by wybiral

HTML

<script src="http://www.js.do/sound/js/riffwave.js"></script>
<script src="http://www.numericjs.com/lib/numeric-1.2.4.min.js"></script>
<div id="response"></div>

JavaScript

function ringBuffer(data, length, decay, rate) {
    var index, phase = data.length;
    length = Math.floor(rate * length);
    decay *= 0.5;
    var out = data.slice(0);
    for (var i = phase; i < length; i++) {
        index = i - phase;
        out.push((out[index] + out[index + 1]) * decay);
    }
    return out;
}

function pluck(freq, length, decay, rate) {
    var phase = Math.floor(rate / freq);
    var sample = [];
    for (var i = 0; i < phase; i++) {
        sample.push(Math.random() * 2 - 1);
    }
    return ringBuffer(sample, length, decay, rate);
}

function encode(data) {
    return data.map(function(x) {
        return Math.min(255, Math.max(0, Math.floor((x / 2 + 0.5) * 255)));
    });
}

$(function() {
    var wave = new RIFFWAVE();
    wave.Make(encode(pluck(110, 1.0, 0.99, 8000)));
    var audio = new Audio(wave.dataURI);
    audio.play();
});