DrumKit score

{ time, instrument [, intensity] }

by jmchen

HTML

<div>
    <button id='play' style="display: block">Play</button>
</div>
<div>
Set bpm <input id='bpm' value=120 style='width:6em'></input>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src='https://jyunming-chen.github.io/WebAudio/js/shared.js'></script>

CSS

div {
    margin: 15px;
}

JavaScript

function playSound2(buffer, time, intensity) {
    var gainNode = context.createGain();
    var source = context.createBufferSource();
    source.buffer = buffer;

    // Connect source to a gain node
    source.connect(gainNode);
    // Connect gain node to destination
    gainNode.connect(context.destination);
    
    var gainval = intensity || 0.15;    
    gainNode.gain.value = gainval;

    source[source.start ? 'start' : 'noteOn'](time);
}


//////////////////////////////////////////////////////////////////////////////
var RhythmSample = function () {
    loadSounds(this, {
        kick: 'https://jyunming-chen.github.io/WebAudio/kick.wav',
        snare: 'https://jyunming-chen.github.io/WebAudio/snare.wav',
        hihat: 'https://jyunming-chen.github.io/WebAudio/hihat.wav'
    });
};


RhythmSample.prototype.playScore = function (score) {
    // start scheduling
    // We'll start playing the rhythm 100 milliseconds from "now"
    var startTime = context.currentTime + 0.100;
    // tempo in BPM (beat per minute)
    var eighthNoteTime = (60 / tempo) / 2; // seconds per eighthNote
    for (var bar = 0; bar < 2; bar++) {
        var time = startTime + bar * 8 * eighthNoteTime;

        for (var ii = 0; ii < score.length; ii++) {
            if (score[ii].instrument == 'k') playSound2(this.kick, time + score[ii].time * eighthNoteTime, score[ii].intensity);
            if (score[ii].instrument == 's') playSound2(this.snare, time + score[ii].time * eighthNoteTime, score[ii].intensity);
            if (score[ii].instrument == 'h') playSound2(this.hihat, time + score[ii].time * eighthNoteTime, score[ii].intensity);
        }
    }

}

$('#play').click(function () {
    sample.playScore(score1);
});

$('#bpm').on('keyup', function (e) {
    if (e.keyCode === 13) {
        tempo = $('#bpm').val();
        alert('tempo: ' + tempo);
    }
});

/////////////////////////////////////////////////////////////////////////////////////////
var sample = new...