我正在尝试制作一个可以慢慢提高速度的节拍器,让我可以在不必停止演奏来打开我的手持节拍器的情况下进行锻炼。我正在使用一个循环来播放每个小节,并试图让一个停止按钮工作,document.getElementById
并addEventListener
在循环的每一次通过时寻找停止按钮的点击。使用console.log
,我可以看到每次单击停止按钮都会出现,但是当我尝试使用停止节拍循环时,source.noteOff(context.currentTime)
我什么也得不到。任何正确方向的建议或观点将不胜感激。
html是:
<html>
<script type="text/javascript" src="file:///Users/katri/rails_projects/metronome/metronome2.js"></script>
<script type="text/javascript" src="file:///Users/katri/rails_projects/metronome/buffer-loader.js"></script>
<input type="button" onClick="startLoop();" value="Play Loop!">
<input type="button" id="stop" value="Stop Loop!">
</html>
有问题的javascript是:
var startTime = context.currentTime;
var tempo = 80; // BPM (beats per minute)
var eighthNoteTime = (60 / tempo) / 2;
var totalTime = startTime;
for (var bar = 0; bar < 2; bar++) {
document.getElementById('stop').addEventListener('click', function() {
source.noteOff(context.currentTime);
});
eighthNoteTime = (60 / tempo) / 2;
// Play the bass (kick) drum on beats 1, 3, 4, 5 & 7
playSound(kick, totalTime);
playSound(kick, totalTime + 1 * eighthNoteTime);
playSound(kick, totalTime + 3 * eighthNoteTime);
playSound(kick, totalTime + 4 * eighthNoteTime);
playSound(kick, totalTime + 5 * eighthNoteTime);
playSound(kick, totalTime + 7 * eighthNoteTime);
// Play the snare drum on beats 3, 7
playSound(snare, totalTime + 2 * eighthNoteTime);
playSound(snare, totalTime + 6 * eighthNoteTime);
totalTime = totalTime + 8 * eighthNoteTime;
tempo = tempo+5;
}
}
function playSound(soundIndex, time) {
var source = context.createBufferSource();
source.buffer = bufferLoader.bufferList[soundIndex];
source.connect(context.destination);
source.noteOn(time);
}