DrumKit Example

A basic example of creating an oscillator to play a tone

by jmchen

HTML

<div>
    <button id='play' style="display: block">Play</button>
</div>
<hr>
<div id="container">
    <canvas id="cnvs"></canvas>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r70/three.min.js"></script>
<script src="https://dl.dropboxusercontent.com/u/3587259/Code/Threejs/OrbitControls.js">
    
</script>
<script src='https://jyunming-chen.github.io/WebAudio/js/shared.js'></script>

CSS

div {
    margin-top: 5em;
}
#container {
    width:60vw;
    height: 60vw;
    float:left;
    background-color:pink;
    margin: 10px;
}

JavaScript

//////////////////////////////////////////////////////////////////////////////
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.play = function () {
    // We'll start playing the rhythm 100 milliseconds from "now"
    var startTime = context.currentTime + 0.100;
    var tempo = 120; // BPM (beats per minute)
    var eighthNoteTime = (60 / tempo) / 2;

    // Play 2 bars of the following:
    for (var bar = 0; bar < 12; bar++) {
        var time = startTime + bar * 8 * eighthNoteTime;
        // Play the bass (kick) drum on beats 1, 5
        playSound(this.kick, time);
        playSound(this.kick, time + 4 * eighthNoteTime);

        // Play the snare drum on beats 3, 7
        playSound(this.snare, time + 2 * eighthNoteTime);
        playSound(this.snare, time + 6 * eighthNoteTime);

        // Play the hi-hat every eighthh note.
        for (var i = 0; i < 8; ++i) {
            playSound(this.hihat, time + i * eighthNoteTime);
        }
    }
};

/////////////////////////////////////////////////////////////////////////////////////////
var sample = new RhythmSample();
/*
document.querySelector('button').addEventListener('click', function () {
    sample.play();
});
*/
$('#play').click (function() {
    sample.play();
});
// for touch devices
$("#play").on ("touchend", function() {
    sample.play();
});

///////////////////////////////////////////////////////////////////////////////////
var clock = new THREE.Clock();
var scene, renderer, camera;
var plane, cyl, cyl2;
var theCanvasFrame;

init();
animate();

function init() {
    var theCanvas = document.getElementById("cnvs");
    theCanvasFrame = document.getElementById("container");

    renderer = new THREE.WebGLRenderer({
        canvas: theCanvas,
       ...