clicktone 3.0.3 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +117 -134
  2. package/package.json +5 -5
package/README.md CHANGED
@@ -1,46 +1,37 @@
1
1
  # clicktone
2
2
 
3
- A lightweight helper for UI sound feedback. It wraps the Web Audio API with a tiny, event-based API and a rock-solid iOS/Safari unlock.
3
+ Play UI sounds through the Web Audio API, with typed events, a shared audio context, and audio unlocking for iOS and Safari.
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/clicktone.svg?colorB=brightgreen)](https://www.npmjs.com/package/clicktone)
6
6
  [![NPM Downloads](https://img.shields.io/npm/dm/clicktone.svg?style=flat)](https://www.npmjs.com/package/clicktone)
7
7
 
8
8
  [Demo](https://codepen.io/ux-ui/pen/yLwbmMr)
9
9
 
10
- ---
11
-
12
- ## Features
13
-
14
- - Single shared `AudioContext` for every instance (no iOS context-limit issues).
15
- - Reliable autoplay unlock: eager gesture listeners, synchronous resume, silent priming ping, re-resume on `visibilitychange`.
16
- - Self-healing on iOS/Safari: detects a "zombie" context after tab/app switch or lock-screen and transparently rebuilds it on the next interaction.
17
- - Automatic format fallback via `canPlayType` (great for Safari, which dislikes OGG/Opus).
18
- - Shared decode cache, throttling, volume control, loop playback, stop control, and subtle pitch variation.
19
- - Event-based (`EventTarget`) with a typed `on()` / `once()` API; `play()` also returns a `Promise`.
20
-
21
- ---
22
-
23
10
  ## Installation
24
11
 
25
12
  ```bash
26
13
  npm install clicktone
27
14
  ```
28
15
 
29
- ---
16
+ ## Quick start
30
17
 
31
- ## Quick Start
18
+ In a browser app with a bundler, serve a short audio file at `/audio/click.mp3`. Add a button, then run the TypeScript module after the button exists:
19
+
20
+ ```html
21
+ <button id="click-button" type="button">Play sound</button>
22
+ ```
32
23
 
33
24
  ```ts
34
25
  import { ClickTone } from 'clicktone';
35
26
 
36
- const button = document.getElementById('clickBtn');
27
+ const button = document.getElementById('click-button');
37
28
 
38
29
  if (!button) {
39
- throw new Error('Demo DOM is not ready');
30
+ throw new Error('Click button was not found');
40
31
  }
41
32
 
42
33
  const sound = new ClickTone({
43
- src: new URL('./assets/click.mp3', import.meta.url).href,
34
+ src: '/audio/click.mp3',
44
35
  volume: 0.7,
45
36
  throttle: 100,
46
37
  pitchVariation: 0.08,
@@ -48,130 +39,145 @@ const sound = new ClickTone({
48
39
  });
49
40
 
50
41
  sound.on('error', (error) => console.error(error));
51
- button.addEventListener('click', () => sound.play());
42
+ button.addEventListener('click', () => void sound.play());
52
43
  ```
53
44
 
54
- The `src` option also accepts DOM elements: an `HTMLSourceElement`, an `HTMLAudioElement` (its child `<source>` elements become the fallback list), or `{ id }` referencing either of those by id.
45
+ Each click plays the sound. `preload: true` fetches and decodes it in advance; playback still needs a user interaction to unlock browser audio. Call `sound.destroy()` when you no longer need the instance.
46
+
47
+ ## API
48
+
49
+ `new ClickTone(options)` creates a sound instance that uses the shared audio engine. The package also exports its TypeScript types, including `ClickToneOptions`, `SoundInput`, `PlayOptions`, and `ReplayBehavior`.
55
50
 
56
- Pass an array to enable automatic format fallback:
51
+ ### Options
52
+
53
+ | Option | Type | Default | Description |
54
+ | --- | --- | --- | --- |
55
+ | `src` | `SoundInput` | Required | Audio source or list of format alternatives; see below. |
56
+ | `volume` | `number` | `1` | Playback volume, from `0` to `1`. |
57
+ | `muted` | `boolean` | `false` | Start muted. Change it later with `setMuted()` or `toggleMuted()`. |
58
+ | `throttle` | `number` | `0` | Minimum interval between accepted `play()` calls, in milliseconds. Earlier requests are ignored. |
59
+ | `pitchVariation` | `number` | `0` | Random playback-rate variation, from `0` to `1`, so repeated clicks do not sound identical. |
60
+ | `preload` | `boolean` | `false` | Fetch and decode the sound when the instance is created. |
61
+ | `loop` | `boolean` | `false` | Keep playing until `stop()` is called. |
62
+ | `replay` | `ReplayBehavior` | `'overlap'` | What happens when this instance is already playing; see Replay behavior. |
63
+ | `debug` | `boolean` | `false` | Log internal errors to the console as well as emitting the `error` event. |
64
+
65
+ `SoundInput` accepts one source or an array of sources:
57
66
 
58
67
  ```ts
59
- const sound = new ClickTone({
60
- src: ['./click.aac', './click.ogg', './click.mp3'],
61
- });
68
+ type SoundSource =
69
+ | string
70
+ | URL
71
+ | { src: string; type?: string }
72
+ | { id: string }
73
+ | HTMLSourceElement
74
+ | HTMLAudioElement;
75
+
76
+ type SoundInput = SoundSource | SoundSource[];
62
77
  ```
63
78
 
64
- ---
79
+ For an `HTMLAudioElement`, its child `<source>` elements form the fallback list. `{ id }` refers to an audio or source element by its DOM id. For a list, ClickTone prefers a format that `canPlayType` reports as playable; if none is recognized, it uses the first source.
65
80
 
66
- ## API
81
+ ### Methods
67
82
 
68
- - `new ClickTone(options)` — creates a sound instance bound to the shared audio engine.
69
- - `sound.play(srcOrOptions?)` — starts playback; returns a `Promise` that resolves when playback ends (or when a loop starts).
70
- - `sound.preload(src?)` — fetches and decodes the buffer ahead of time.
71
- - `sound.stop()` — stops active playback on this instance.
72
- - `sound.unlock()` — resumes the shared `AudioContext` inside a user gesture.
73
- - `sound.destroy()` — stops playback and removes listeners for this instance.
74
- - `sound.on(type, fn)` / `sound.once(type, fn)` — typed event subscriptions; return an unsubscribe function.
75
- - `ClickTone.unlock()` — static helper to unlock the shared context from a global gesture handler.
76
- - `ClickTone.unlocked` — whether the shared context is currently unlocked.
83
+ The following methods belong to the `sound` instance from Quick start:
77
84
 
78
- ---
85
+ | Method | Returns | Description |
86
+ | --- | --- | --- |
87
+ | `play(input?)` | `Promise<void>` | Play the configured sound, a different `SoundInput`, or a `PlayOptions` object. Resolves when non-looped playback ends or when a loop starts. |
88
+ | `preload()` | `Promise<AudioBuffer \| undefined>` | Fetch and decode the configured sound. Returns `undefined` when no buffer is available or loading fails. |
89
+ | `stop()` | `void` | Stop all active playback on this instance. |
90
+ | `unlock()` | `void` | Resume the shared audio context. Call inside a user gesture. |
91
+ | `setVolume(value)` | `void` | Set playback volume from `0` to `1`. |
92
+ | `setMuted(muted)` | `void` | Set the muted state. |
93
+ | `toggleMuted()` | `boolean` | Toggle muting and return the new muted state. |
94
+ | `on(type, listener)` | `() => void` | Subscribe to an event and return an unsubscribe function. The listener receives the event detail. |
95
+ | `once(type, listener)` | `void` | Subscribe to the next occurrence of an event. The listener receives the event detail. |
96
+ | `destroy()` | `void` | Stop playback and release this instance's audio resources and lifecycle listeners. |
79
97
 
80
- ## Options
98
+ Read the current state through `sound.playing`, `sound.volume`, and `sound.muted`.
81
99
 
82
- | Option | Type | Default | Description |
83
- | --- | --- | --- | --- |
84
- | `src` | `string \| URL \| {src,type?} \| {id} \| HTMLSourceElement \| HTMLAudioElement \| Array<…>` | — | Audio source(s). Pass an array to enable automatic format fallback. |
85
- | `volume` | `number` | `1` | Playback volume `0`–`1`. |
86
- | `muted` | `boolean` | `false` | Start muted. Toggle later via `setMuted()` / `toggleMuted()`. |
87
- | `throttle` | `number` | `0` | Debounce interval in ms. Requests arriving sooner are ignored. |
88
- | `pitchVariation` | `number` | `0` | `0`–`1`. Random playback-rate jitter so repeated clicks don't sound identical. |
89
- | `preload` | `boolean` | `false` | Fetch and decode the buffer on construction. |
90
- | `loop` | `boolean` | `false` | Keep playback running until `stop()` is called. |
91
- | `replay` | `'overlap' \| 'interrupt' \| 'ignore-if-playing' \| 'restart'` | `'overlap'` | Behavior when `play()` is called while this instance is already playing. |
92
- | `debug` | `boolean` | `false` | Log internal errors to the console (in addition to the `error` event). |
100
+ `ClickTone.unlock()` resumes the shared context from a global gesture handler. `ClickTone.unlocked` reports whether it has been unlocked.
101
+
102
+ A `PlayOptions` object can override `src`, `loop`, and `replay` for one call. For example, continuing with the `sound` instance above and an audio file at `/audio/win.mp3`:
103
+
104
+ ```ts
105
+ await sound.play({ src: '/audio/win.mp3', replay: 'interrupt' });
106
+ ```
93
107
 
94
- ---
108
+ Loading, decoding, and playback errors are reported through the `error` event. Listen for that event even when awaiting `play()` or `preload()`.
95
109
 
96
- ## Events
110
+ ### Events
97
111
 
98
- `ClickTone` extends `EventTarget`. Subscribe with the typed `on()` / `once()` helpers or with native `addEventListener`.
112
+ `ClickTone` extends `EventTarget`. Use the typed `on()` and `once()` helpers, or native `addEventListener`. Native listeners receive a `CustomEvent` with the payload in `event.detail`.
99
113
 
100
- | Event | Detail | Fired when |
114
+ | Event | When | Payload |
101
115
  | --- | --- | --- |
102
- | `play` | — | A buffer source has started. |
103
- | `end` | — | Playback finished naturally. |
104
- | `stop` | — | Active playback was stopped explicitly. |
105
- | `unlock` | — | The shared `AudioContext` became playable. |
106
- | `load` | `AudioBuffer` | A source was fetched and decoded. |
107
- | `error` | `Error` | Loading, decoding, or playback failed. |
116
+ | `play` | A buffer source starts. | None |
117
+ | `end` | Playback finishes naturally. | None |
118
+ | `stop` | Active playback is stopped explicitly. | None |
119
+ | `unlock` | The shared audio context becomes playable. | None |
120
+ | `load` | `preload()` fetches and decodes a source. | `AudioBuffer` |
121
+ | `error` | Loading, decoding, or playback fails. | `Error` |
122
+
123
+ Continuing with `sound` from Quick start:
108
124
 
109
125
  ```ts
110
126
  const off = sound.on('end', () => console.log('finished'));
111
- sound.on('error', (error) => console.error(error));
112
127
  sound.once('unlock', () => console.log('audio unlocked'));
113
128
 
129
+ // When this subscription is no longer needed:
114
130
  off();
115
-
116
- await sound.play();
117
131
  ```
118
132
 
119
- ---
133
+ ## Replay behavior
120
134
 
121
- ## Methods
135
+ - `'overlap'` (default): every accepted `play()` call starts another buffer source.
136
+ - `'interrupt'`: stop active playback, then play the requested sound.
137
+ - `'ignore-if-playing'`: ignore the request while this instance is playing.
138
+ - `'restart'`: stop active playback and start again, bypassing `throttle`.
122
139
 
123
- ```ts
124
- await sound.play();
125
- await sound.play({ loop: true });
126
- await sound.play({ src: '/win.mp3', replay: 'interrupt' });
127
- await sound.preload();
128
- sound.unlock();
129
- sound.stop();
130
- sound.playing;
131
- sound.setVolume(0.5);
132
- sound.setMuted(true);
133
- sound.toggleMuted();
134
- sound.on('end', () => {});
135
- sound.destroy();
136
-
137
- ClickTone.unlock();
138
- ClickTone.unlocked;
139
- ```
140
+ For looped playback, `play()` resolves once the loop starts. Call `stop()` to end it.
140
141
 
141
- ### Replay behavior
142
+ ## Provide format alternatives
142
143
 
143
- - `overlap` (default): preserve classic SFX behavior — every accepted `play()` call starts another buffer source.
144
- - `interrupt`: stop active playback, then start the requested sound.
145
- - `ignore-if-playing`: ignore the request while this instance is already playing.
146
- - `restart`: stop active playback and start again, bypassing `throttle`.
144
+ In the same browser setup as Quick start, supply your audio files in more than one format:
147
145
 
148
- For looped playback, `play()` resolves after the loop starts rather than waiting forever for a natural end. Use `stop()` to end it.
149
-
150
- ---
146
+ ```ts
147
+ const fallbackSound = new ClickTone({
148
+ src: ['/audio/click.aac', '/audio/click.ogg', '/audio/click.mp3'],
149
+ });
150
+ ```
151
151
 
152
- ## Browser support
152
+ ## Play a loop and a completion sound
153
153
 
154
- Mobile browsers (especially Safari on iOS) block audio until the user interacts with the page. An `AudioContext` must be resumed synchronously inside a user gesture, and iOS caps the number of contexts you may create. ClickTone handles all of this:
154
+ Using the `ClickTone` import from Quick start, serve files at `/audio/flying.mp3` and `/audio/bonus.mp3`. Create separate instances for the continuous sound and the completion sound:
155
155
 
156
- - One shared `AudioContext` (with `latencyHint: 'interactive'`) — one unlock unlocks every instance.
157
- - Global gesture listeners (`pointerdown` / `pointerup` / `touchstart` / `touchend` / `keydown`) resume the context on the first interaction anywhere on the page.
158
- - A silent priming ping is played right after unlock, and the context is re-resumed on `visibilitychange`.
159
- - Lifecycle recovery for Safari/iOS: after a tab switch, app switch, or lock-screen, WebKit can leave the context in a "zombie" state (it reports `running` but stays silent). ClickTone probes for this on return and, if the context is dead, rebuilds it inside the next user gesture — buffers re-decode and the gain graph rebinds automatically.
160
- - Decoded buffers are cached and shared, so the first click is not delayed by the network.
156
+ ```ts
157
+ const flying = new ClickTone({
158
+ src: '/audio/flying.mp3',
159
+ loop: true,
160
+ preload: true,
161
+ });
161
162
 
162
- Pass `preload: true` (or call `sound.preload()`) so the buffer is decoded ahead of the first click. Include an MP3/AAC source for Safari — OGG/Opus is not reliably supported there.
163
+ const bonus = new ClickTone({
164
+ src: '/audio/bonus.mp3',
165
+ preload: true,
166
+ });
163
167
 
164
- ```ts
165
- await sound.preload();
168
+ // Inside a user interaction that starts the process:
169
+ await flying.play();
166
170
 
167
- document.addEventListener('pointerdown', () => ClickTone.unlock(), { once: true });
171
+ // When the process finishes:
172
+ flying.stop();
173
+ await bonus.play();
168
174
  ```
169
175
 
170
- ---
176
+ The two parts run at different points in your app's lifecycle. Destroy both instances when that part of the app is removed.
171
177
 
172
178
  ## Vue 3
173
179
 
174
- Use `ClickTone` directly from the main entry — the package stays framework-agnostic.
180
+ Import `ClickTone` from the main package entry. This component uses the same `/audio/click.mp3` file as Quick start:
175
181
 
176
182
  ```vue
177
183
  <script setup lang="ts">
@@ -182,11 +188,12 @@ const sound = shallowRef<ClickTone | null>(null);
182
188
 
183
189
  onMounted(() => {
184
190
  sound.value = new ClickTone({
185
- src: new URL('./assets/click.mp3', import.meta.url).href,
191
+ src: '/audio/click.mp3',
186
192
  volume: 0.7,
187
193
  pitchVariation: 0.08,
188
194
  preload: true,
189
195
  });
196
+ sound.value.on('error', (error) => console.error(error));
190
197
  });
191
198
 
192
199
  onBeforeUnmount(() => {
@@ -196,48 +203,24 @@ onBeforeUnmount(() => {
196
203
  </script>
197
204
 
198
205
  <template>
199
- <button @click="sound?.play()">Click</button>
206
+ <button type="button" @click="sound?.play()">Play sound</button>
200
207
  </template>
201
208
  ```
202
209
 
203
- ---
204
-
205
- ## Advanced usage
206
-
207
- Use one `ClickTone` instance for a long-running process sound and separate instances for terminal SFX:
208
-
209
- ```ts
210
- const flying = new ClickTone({
211
- src: new URL('./assets/flying.mp3', import.meta.url).href,
212
- loop: true,
213
- preload: true,
214
- });
210
+ ## Browser support
215
211
 
216
- const bonus = new ClickTone({
217
- src: new URL('./assets/bonus.mp3', import.meta.url).href,
218
- preload: true,
219
- });
212
+ Browsers can block audio until the user interacts with the page. On iOS and Safari, the audio context needs to be resumed inside a user gesture. ClickTone shares one `AudioContext` between instances, requests `latencyHint: 'interactive'`, and installs gesture listeners for `pointerdown`, `pointerup`, `touchstart`, `touchend`, and `keydown`.
220
213
 
221
- await flying.play();
214
+ After unlocking, the engine plays a silent priming ping. It also handles `visibilitychange` and `pageshow` to resume audio after the page returns. On Safari and iOS, a context may report `running` while its clock is frozen. The engine checks for this state and rebuilds the context on the next user interaction when needed. Buffers are decoded again and gain nodes are reconnected.
222
215
 
223
- flying.stop();
224
- await bonus.play();
225
- ```
216
+ Decoded buffers are cached across instances. Use `preload: true` or `sound.preload()` to load them before the first click. Include an MP3 or AAC source for Safari, where OGG and Opus support varies.
226
217
 
227
- Encode the interruption policy on a single instance:
218
+ To request an explicit unlock in the browser setup from Quick start:
228
219
 
229
220
  ```ts
230
- const terminal = new ClickTone({
231
- src: new URL('./assets/explosion.mp3', import.meta.url).href,
232
- replay: 'interrupt',
233
- preload: true,
234
- });
235
-
236
- await terminal.play();
221
+ document.addEventListener('pointerdown', () => ClickTone.unlock(), { once: true });
237
222
  ```
238
223
 
239
- ---
240
-
241
224
  ## License
242
225
 
243
226
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clicktone",
3
- "version": "3.0.3",
3
+ "version": "3.0.4",
4
4
  "description": "A lightweight helper for UI sound feedback. It wraps the Web Audio API with a tiny, event-based API and a rock-solid iOS/Safari unlock.",
5
5
  "author": "Maxim <m@nilmuse.com>",
6
6
  "license": "MIT",
@@ -59,10 +59,10 @@
59
59
  "@arethetypeswrong/cli": "^0.18.3",
60
60
  "@biomejs/biome": "2.4.16",
61
61
  "@types/node": "25.9.2",
62
- "@ux-ui/biome-config": "^0.1.0",
63
- "@ux-ui/tsconfig-base": "^0.1.0",
64
- "@ux-ui/tsdown-config": "^0.1.0",
65
- "@ux-ui/vitest-runner": "^0.1.0",
62
+ "@nilmuse/biome-config": "^0.1.3",
63
+ "@nilmuse/tsconfig-base": "^0.1.3",
64
+ "@nilmuse/tsdown-config": "^0.1.3",
65
+ "@nilmuse/vitest-runner": "^0.1.3",
66
66
  "jsdom": "29.1.1",
67
67
  "publint": "^0.3.21",
68
68
  "rimraf": "6.1.3",