この記事の指示に従い、Javascript メトロノームを作成しました。Web Audio API を利用し、audioContext.currentTime
正確なタイミングを実現するためのコアを備えています。
この plunkerで入手できる私のバージョンは、元のバージョンを非常に単純化したもので、Chris Wilson によって作成され、ここで入手できます。私のものを機能させるには、実際のオーディオ ファイルを使用し、オシレーターを介してサウンドを合成しないため、プランカーとこのオーディオ ファイルをダウンロードしてルート フォルダーに配置する必要があります (これはメトロノームの「ティック」サウンドであり、任意のサウンドを使用できます)。
ユーザーがウィンドウを最小化すると、それ以外の場合は非常に正確なメトロノームが即座にひどく途切れ始めるという事実がなければ、それは魅力のように機能します. ここで何が問題なのか本当にわかりません。
Javascript
var context, request, buffer;
var tempo = 120;
var tickTime;
function ticking() {
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(tickTime);
}
function scheduler() {
while (tickTime < context.currentTime + 0.1) { //while there are notes to schedule, play the last scheduled note and advance the pointer
ticking();
tickTime += 60 / tempo;
}
}
function loadTick() {
request = new XMLHttpRequest(); //Asynchronous http request (you'll need a local server)
request.open('GET', 'tick.wav', true); //You need to download the file @ http://s000.tinyupload.com/index.php?file_id=89415137224761217947
request.responseType = 'arraybuffer';
request.onload = function () {
context.decodeAudioData(request.response, function (theBuffer) {
buffer = theBuffer;
});
};
request.send();
}
function start() {
tickTime = context.currentTime;
scheduleTimer = setInterval(function () {
scheduler();
}, 25);
}
window.onload = function () {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
loadTick();
start();
};