metronome + score
by pkin159
HTML
<div>
<button id='play' class='mybutton'>toggle 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;
}
.mybutton {
margin: 10px;
display: block;
}
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.5;
gainNode.gain.value = gainval;
source[source.start ? 'start' : 'noteOn'](time);
/////////////////////////////////
// source.start (when, in seconds)
// The 'when' parameter defines when the play will start.
// If when represents a time in the past, the play will start immediately.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/start
}
////////////////////////////////////////////////////////////////////////////
// note:
// preceding spaces of sound samples need to be trimmed clearly
// note that saving the trimmed sample DOES NOT work well
// for mp3 files (works ok for wav files)
// (metronome_click.mp3 has preceding spaces, no matter how I trimmed
//
//////////////////////////////////////////////////////////////////////////////
var RhythmSample = function () {
loadSounds(this, {
click: 'https://jyunming-chen.github.io/WebAudio/metronome_click.wav',
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'
});
};
// play score of one bar
RhythmSample.prototype.playSequence = function (score) {
var startTime = context.currentTime; // in seconds, from webaudio
var eighthNoteTime = 60/tempo/2;;
for (var ii = 0; ii < score.length; ii++) {
if (score[ii].instrument == 'k')
playSound2(this.kick, startTime + score[ii].time * eighthNoteTime, score[ii].intensity);
if (score[ii].instrument == 's')
playSound2(this.snare, startTime + score[ii].time *...