metronome
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, {
click: 'https://jyunming-chen.github.io/WebAudio/metronome_click.mp3',
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.playOnce = 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);
}
}
}
function playClick () {
playSound2 (sample.click, 0, 1);
if (metronomeOn) {
setTimeout (function(){playClick();}, quarterNoteTime);
}
}
$('#play').click(function () {
metronomeOn = !metronomeOn;
if (metronomeOn) playClick(); ...