clicktone 3.0.0 → 3.0.1

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 +125 -84
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -2,21 +2,33 @@
2
2
 
3
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.
4
4
 
5
+ [![npm](https://img.shields.io/npm/v/clicktone.svg?colorB=brightgreen)](https://www.npmjs.com/package/clicktone)
6
+ [![NPM Downloads](https://img.shields.io/npm/dm/clicktone.svg?style=flat)](https://www.npmjs.com/package/clicktone)
7
+
8
+ [Demo](https://codepen.io/ux-ui/pen/yLwbmMr)
9
+
10
+ ---
11
+
12
+ ## Features
13
+
5
14
  - Single shared `AudioContext` for every instance (no iOS context-limit issues).
6
15
  - Reliable autoplay unlock: eager gesture listeners, synchronous resume, silent priming ping, re-resume on `visibilitychange`.
7
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.
8
17
  - Automatic format fallback via `canPlayType` (great for Safari, which dislikes OGG/Opus).
9
18
  - Shared decode cache, throttling, volume control, loop playback, stop control, and subtle pitch variation.
10
19
  - Event-based (`EventTarget`) with a typed `on()` / `once()` API; `play()` also returns a `Promise`.
11
- - [Demo](https://codepen.io/ux-ui/pen/yLwbmMr)
12
20
 
13
- ## Install
21
+ ---
22
+
23
+ ## Installation
14
24
 
15
25
  ```bash
16
26
  npm install clicktone
17
27
  ```
18
28
 
19
- ## Usage (TypeScript)
29
+ ---
30
+
31
+ ## Quick Start
20
32
 
21
33
  ```ts
22
34
  import { ClickTone } from 'clicktone';
@@ -28,12 +40,7 @@ if (!button) {
28
40
  }
29
41
 
30
42
  const sound = new ClickTone({
31
- // A single source…
32
43
  src: new URL('./assets/click.mp3', import.meta.url).href,
33
-
34
- // …or a fallback list; the best supported format is picked automatically:
35
- // src: ['./click.aac', './click.ogg', './click.mp3'],
36
-
37
44
  volume: 0.7,
38
45
  throttle: 100,
39
46
  pitchVariation: 0.08,
@@ -46,63 +53,105 @@ button.addEventListener('click', () => sound.play());
46
53
 
47
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.
48
55
 
49
- ## Usage (Vue 3)
56
+ Pass an array to enable automatic format fallback:
50
57
 
51
- ```vue
52
- <script setup lang="ts">
53
- import { onBeforeUnmount, onMounted, shallowRef } from 'vue';
54
- import { ClickTone } from 'clicktone';
58
+ ```ts
59
+ const sound = new ClickTone({
60
+ src: ['./click.aac', './click.ogg', './click.mp3'],
61
+ });
62
+ ```
55
63
 
56
- const sound = shallowRef<ClickTone | null>(null);
64
+ ---
57
65
 
58
- onMounted(() => {
59
- sound.value = new ClickTone({
60
- src: new URL('./assets/click.mp3', import.meta.url).href,
61
- volume: 0.7,
62
- pitchVariation: 0.08,
63
- preload: true,
64
- });
65
- });
66
+ ## API
66
67
 
67
- onBeforeUnmount(() => {
68
- sound.value?.destroy();
69
- sound.value = null;
70
- });
71
- </script>
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.
72
77
 
73
- <template>
74
- <button @click="sound?.play()">Click</button>
75
- </template>
76
- ```
78
+ ---
79
+
80
+ ## Options
81
+
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). |
93
+
94
+ ---
77
95
 
78
96
  ## Events
79
97
 
80
- `ClickTone` extends `EventTarget`. Subscribe with the typed `on()` / `once()` helpers (which return an unsubscribe function) or with native `addEventListener`.
98
+ `ClickTone` extends `EventTarget`. Subscribe with the typed `on()` / `once()` helpers or with native `addEventListener`.
99
+
100
+ | Event | Detail | Fired when |
101
+ | --- | --- | --- |
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. |
81
108
 
82
109
  ```ts
83
110
  const off = sound.on('end', () => console.log('finished'));
84
111
  sound.on('error', (error) => console.error(error));
85
112
  sound.once('unlock', () => console.log('audio unlocked'));
86
- sound.on('stop', () => console.log('stopped'));
87
113
 
88
114
  off();
89
115
 
90
- // play() also resolves when playback ends:
91
116
  await sound.play();
92
117
  ```
93
118
 
94
- | Event | Detail | Fired when |
95
- |:---------|:--------------|:--------------------------------------------|
96
- | `play` | — | A buffer source has started. |
97
- | `end` | — | Playback finished naturally. |
98
- | `stop` | — | Active playback was stopped explicitly. |
99
- | `unlock` | — | The shared `AudioContext` became playable. |
100
- | `load` | `AudioBuffer` | A source was fetched and decoded. |
101
- | `error` | `Error` | Loading, decoding, or playback failed. |
119
+ ---
120
+
121
+ ## Methods
102
122
 
103
- ## iOS / Safari unlock
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();
104
136
 
105
- 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:
137
+ ClickTone.unlock();
138
+ ClickTone.unlocked;
139
+ ```
140
+
141
+ ### Replay behavior
142
+
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`.
147
+
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
+ ---
151
+
152
+ ## Browser support
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:
106
155
 
107
156
  - One shared `AudioContext` (with `latencyHint: 'interactive'`) — one unlock unlocks every instance.
108
157
  - Global gesture listeners (`pointerdown` / `pointerup` / `touchstart` / `touchend` / `keydown`) resume the context on the first interaction anywhere on the page.
@@ -115,54 +164,45 @@ Pass `preload: true` (or call `sound.preload()`) so the buffer is decoded ahead
115
164
  ```ts
116
165
  await sound.preload();
117
166
 
118
- // Or unlock the shared context on a known first interaction:
119
167
  document.addEventListener('pointerdown', () => ClickTone.unlock(), { once: true });
120
168
  ```
121
169
 
122
- ## Options
170
+ ---
123
171
 
124
- | Option | Type | Default | Description |
125
- |:-----------------|:--------------------------------------------------------------------------------------------|:-------:|:-----------------------------------------------------------------------------|
126
- | `src` | `string \| URL \| {src,type?} \| {id} \| HTMLSourceElement \| HTMLAudioElement \| Array<…>` | — | Audio source(s). Pass an array to enable automatic format fallback. |
127
- | `volume` | `number` | `1` | Playback volume `0`–`1`. |
128
- | `muted` | `boolean` | `false` | Start muted. Toggle later via `setMuted()` / `toggleMuted()`. |
129
- | `throttle` | `number` | `0` | Debounce interval in ms. Requests arriving sooner are ignored. |
130
- | `pitchVariation` | `number` | `0` | `0`–`1`. Random playback-rate jitter so repeated clicks don't sound identical. |
131
- | `preload` | `boolean` | `false` | Fetch and decode the buffer on construction. |
132
- | `loop` | `boolean` | `false` | Keep playback running until `stop()` is called. |
133
- | `replay` | `'overlap' \| 'interrupt' \| 'ignore-if-playing' \| 'restart'` | `'overlap'` | Behavior when `play()` is called while this instance is already playing. |
134
- | `debug` | `boolean` | `false` | Log internal errors to the console (in addition to the `error` event). |
172
+ ## Vue 3
135
173
 
136
- ## Methods
174
+ Use `ClickTone` directly from the main entry — the package stays framework-agnostic.
137
175
 
138
- ```ts
139
- await sound.play(); // optionally play(src) to override the source
140
- await sound.play({ loop: true });
141
- await sound.play({ src: '/win.mp3', replay: 'interrupt' });
142
- await sound.preload(); // optionally preload(src)
143
- sound.unlock();
144
- sound.stop();
145
- sound.playing; // whether this instance has active playback
146
- sound.setVolume(0.5); // smoothly ramped
147
- sound.setMuted(true);
148
- sound.toggleMuted();
149
- sound.on('end', () => {}); // on(type, fn) / once(type, fn)
150
- sound.destroy();
176
+ ```vue
177
+ <script setup lang="ts">
178
+ import { onBeforeUnmount, onMounted, shallowRef } from 'vue';
179
+ import { ClickTone } from 'clicktone';
151
180
 
152
- ClickTone.unlock(); // static: unlock the shared context
153
- ClickTone.unlocked; // static: whether the shared context is unlocked
154
- ```
181
+ const sound = shallowRef<ClickTone | null>(null);
155
182
 
156
- ### Replay behavior
183
+ onMounted(() => {
184
+ sound.value = new ClickTone({
185
+ src: new URL('./assets/click.mp3', import.meta.url).href,
186
+ volume: 0.7,
187
+ pitchVariation: 0.08,
188
+ preload: true,
189
+ });
190
+ });
157
191
 
158
- - `overlap` (default): preserve classic SFX behavior — every accepted `play()` call starts another buffer source.
159
- - `interrupt`: stop active playback, then start the requested sound.
160
- - `ignore-if-playing`: ignore the request while this instance is already playing.
161
- - `restart`: stop active playback and start again, bypassing `throttle`.
192
+ onBeforeUnmount(() => {
193
+ sound.value?.destroy();
194
+ sound.value = null;
195
+ });
196
+ </script>
162
197
 
163
- For looped playback, `play()` resolves after the loop starts rather than waiting forever for a natural end. Use `stop()` to end it.
198
+ <template>
199
+ <button @click="sound?.play()">Click</button>
200
+ </template>
201
+ ```
202
+
203
+ ---
164
204
 
165
- ## Interruptible sounds / game patterns
205
+ ## Advanced usage
166
206
 
167
207
  Use one `ClickTone` instance for a long-running process sound and separate instances for terminal SFX:
168
208
 
@@ -178,14 +218,13 @@ const bonus = new ClickTone({
178
218
  preload: true,
179
219
  });
180
220
 
181
- await flying.play(); // resolves once the loop starts
221
+ await flying.play();
182
222
 
183
- // Later, when the player wins:
184
223
  flying.stop();
185
224
  await bonus.play();
186
225
  ```
187
226
 
188
- You can also encode the interruption policy on a single instance:
227
+ Encode the interruption policy on a single instance:
189
228
 
190
229
  ```ts
191
230
  const terminal = new ClickTone({
@@ -197,6 +236,8 @@ const terminal = new ClickTone({
197
236
  await terminal.play();
198
237
  ```
199
238
 
239
+ ---
240
+
200
241
  ## License
201
242
 
202
243
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clicktone",
3
- "version": "3.0.0",
3
+ "version": "3.0.1",
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": "ux-ui.pro",
6
6
  "license": "MIT",