Skip to content

Commit

Permalink
Allow changing tempo
Browse files Browse the repository at this point in the history
  • Loading branch information
bkeepers committed Apr 26, 2024
1 parent 579b12a commit c21cf41
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
6 changes: 5 additions & 1 deletion demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function onBeat(note) {
}

document.getElementById("enabled")?.addEventListener("change", (e) => {
if (e.target?.checked) {
if ((e.target as HTMLInputElement)?.checked) {
metronome = createMetronome({ tempo: Number(tempoEl.value), onBeat })
metronome.start()
} else {
Expand All @@ -27,3 +27,7 @@ document.getElementById("enabled")?.addEventListener("change", (e) => {
metronome = undefined
}
})

tempoEl.addEventListener("input", () => {
metronome?.setTempo(Number(tempoEl.value))
})
14 changes: 11 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,18 @@ export function createMetronome(config: MetronomeConfig = {}) {
let interval: number | undefined;

// Time in seconds that a bar lasts
const secondsPerBar = 60 / config.tempo! * config.meter![0]
let secondsPerBar: number;

// duration of 16th note in seconds
const secondsPerNote = 60 / config.tempo! / 4
let secondsPerNote: number;

function setTempo(tempo: number) {
config.tempo = tempo
secondsPerBar = 60 / config.tempo! * config.meter![0]
secondsPerNote = 60 / config.tempo! / 4
}

setTempo(config.tempo!)

// Returns the next time that the given note can be played. Given synchronized clocks, any metronome
// playing the same tempo will play the same note of a measure at the same time.
Expand Down Expand Up @@ -159,5 +167,5 @@ export function createMetronome(config: MetronomeConfig = {}) {
requestAnimationFrame(draw);
}

return { start, stop }
return { start, stop, setTempo }
}

0 comments on commit c21cf41

Please sign in to comment.