useTapTempo
Tap tempo with a rolling average and idle reset.
useTapTempo powers the tempo control. Use it with your own input, sound pad or keyboard shortcut.
$ pnpm dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-tap-tempo.json$ npx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-tap-tempo.json$ yarn dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-tap-tempo.json$ bunx --bun shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-tap-tempo.jsonUsage
<script lang="ts">
import { useTapTempo } from "#lib/hooks/use-tap-tempo.svelte.js";
const tempo = useTapTempo({ defaultValue: 120 });
</script>
<button type="button" onclick={(event) => tempo.tap(event)}>Tap</button>
<span>{tempo.value} BPM</span>Call tempo.tap() once per beat. The second tap produces a BPM value; later taps average the last four intervals. A gap longer than two seconds starts a fresh sequence without changing the current value on its first tap. Taps less than 80 ms apart are ignored.
BPM values are always whole numbers. Tapped tempos, value, defaultValue and setValue() round to the nearest integer.
Call tap() from your app's keyboard handler or hotkey library.
Call it during component setup. The options can be an object or a getter. Read value and tapCount from the returned object: they are getters, so destructuring them loses updates.
Options
| Prop | Type | Default |
|---|---|---|
value / defaultValue BPM. | number | 120 (uncontrolled) |
min / max Positive integer BPM bounds. | number | 30 / 600 |
tapTimeout Idle milliseconds before a new sequence. Set at least 60000 / min for slower tempos. | number | 2000 |
disabled / readOnly Prevent taps and value changes. | boolean | false |
onValueChange details.reason: tap, input or keyboard. | (value, details) => void | — |
onValueCommitted Called after a measured tap, including an unchanged value. | (value) => void | — |
Returns
| Prop | Type | Default |
|---|---|---|
value Current integer BPM, clamped to the configured range. | number | — |
tap Record a tap. Pass its native event to include it in change details. | (event?: Event) => void | — |
setValue Change BPM and clear tap history. The default reason is input. | (value, details?) => void | — |
resetTaps Clear tap history without changing BPM. | () => void | — |
tapCount Accepted taps, including the first. Use it to restart visual feedback. | number | 0 |