clicktone 2.1.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.
- package/README.md +126 -85
- package/dist/index.cjs +561 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +74 -0
- package/dist/index.d.ts +74 -2
- package/dist/index.js +559 -0
- package/dist/index.js.map +1 -0
- package/package.json +38 -31
- package/dist/index.cjs.js +0 -3
- package/dist/index.es.js +0 -409
- package/dist/index.umd.js +0 -3
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
declare global {
|
|
3
|
+
interface Window {
|
|
4
|
+
webkitAudioContext?: typeof AudioContext;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
interface SoundDescriptor {
|
|
8
|
+
src: string;
|
|
9
|
+
type?: string;
|
|
10
|
+
}
|
|
11
|
+
type SoundSource = string | URL | SoundDescriptor | {
|
|
12
|
+
id: string;
|
|
13
|
+
} | HTMLSourceElement | HTMLAudioElement;
|
|
14
|
+
type SoundInput = SoundSource | SoundSource[];
|
|
15
|
+
type ReplayBehavior = 'overlap' | 'interrupt' | 'ignore-if-playing' | 'restart';
|
|
16
|
+
interface PlayOptions {
|
|
17
|
+
src?: SoundInput;
|
|
18
|
+
loop?: boolean;
|
|
19
|
+
replay?: ReplayBehavior;
|
|
20
|
+
}
|
|
21
|
+
interface ClickToneOptions {
|
|
22
|
+
src: SoundInput;
|
|
23
|
+
volume?: number;
|
|
24
|
+
muted?: boolean;
|
|
25
|
+
throttle?: number;
|
|
26
|
+
pitchVariation?: number;
|
|
27
|
+
preload?: boolean;
|
|
28
|
+
loop?: boolean;
|
|
29
|
+
replay?: ReplayBehavior;
|
|
30
|
+
debug?: boolean;
|
|
31
|
+
}
|
|
32
|
+
interface ClickToneEventDetail {
|
|
33
|
+
play: undefined;
|
|
34
|
+
end: undefined;
|
|
35
|
+
stop: undefined;
|
|
36
|
+
unlock: undefined;
|
|
37
|
+
load: AudioBuffer;
|
|
38
|
+
error: Error;
|
|
39
|
+
}
|
|
40
|
+
type ClickToneEventType = keyof ClickToneEventDetail;
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/ClickTone.d.ts
|
|
43
|
+
declare class ClickTone extends EventTarget {
|
|
44
|
+
#private;
|
|
45
|
+
constructor({
|
|
46
|
+
src,
|
|
47
|
+
volume,
|
|
48
|
+
muted,
|
|
49
|
+
throttle,
|
|
50
|
+
pitchVariation,
|
|
51
|
+
preload,
|
|
52
|
+
loop,
|
|
53
|
+
replay,
|
|
54
|
+
debug
|
|
55
|
+
}: ClickToneOptions);
|
|
56
|
+
static unlock(): void;
|
|
57
|
+
static get unlocked(): boolean;
|
|
58
|
+
get volume(): number;
|
|
59
|
+
get muted(): boolean;
|
|
60
|
+
get playing(): boolean;
|
|
61
|
+
preload(): Promise<AudioBuffer | undefined>;
|
|
62
|
+
unlock(): void;
|
|
63
|
+
setVolume(value: number): void;
|
|
64
|
+
setMuted(muted: boolean): void;
|
|
65
|
+
toggleMuted(): boolean;
|
|
66
|
+
play(input?: SoundInput | PlayOptions): Promise<void>;
|
|
67
|
+
stop(): void;
|
|
68
|
+
on<T extends ClickToneEventType>(type: T, listener: (detail: ClickToneEventDetail[T]) => void): () => void;
|
|
69
|
+
once<T extends ClickToneEventType>(type: T, listener: (detail: ClickToneEventDetail[T]) => void): void;
|
|
70
|
+
destroy(): void;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
export { ClickTone, type ClickToneEventDetail, type ClickToneEventType, type ClickToneOptions, type PlayOptions, type ReplayBehavior, type SoundDescriptor, type SoundInput, type SoundSource };
|
|
74
|
+
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,74 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
declare global {
|
|
3
|
+
interface Window {
|
|
4
|
+
webkitAudioContext?: typeof AudioContext;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
interface SoundDescriptor {
|
|
8
|
+
src: string;
|
|
9
|
+
type?: string;
|
|
10
|
+
}
|
|
11
|
+
type SoundSource = string | URL | SoundDescriptor | {
|
|
12
|
+
id: string;
|
|
13
|
+
} | HTMLSourceElement | HTMLAudioElement;
|
|
14
|
+
type SoundInput = SoundSource | SoundSource[];
|
|
15
|
+
type ReplayBehavior = 'overlap' | 'interrupt' | 'ignore-if-playing' | 'restart';
|
|
16
|
+
interface PlayOptions {
|
|
17
|
+
src?: SoundInput;
|
|
18
|
+
loop?: boolean;
|
|
19
|
+
replay?: ReplayBehavior;
|
|
20
|
+
}
|
|
21
|
+
interface ClickToneOptions {
|
|
22
|
+
src: SoundInput;
|
|
23
|
+
volume?: number;
|
|
24
|
+
muted?: boolean;
|
|
25
|
+
throttle?: number;
|
|
26
|
+
pitchVariation?: number;
|
|
27
|
+
preload?: boolean;
|
|
28
|
+
loop?: boolean;
|
|
29
|
+
replay?: ReplayBehavior;
|
|
30
|
+
debug?: boolean;
|
|
31
|
+
}
|
|
32
|
+
interface ClickToneEventDetail {
|
|
33
|
+
play: undefined;
|
|
34
|
+
end: undefined;
|
|
35
|
+
stop: undefined;
|
|
36
|
+
unlock: undefined;
|
|
37
|
+
load: AudioBuffer;
|
|
38
|
+
error: Error;
|
|
39
|
+
}
|
|
40
|
+
type ClickToneEventType = keyof ClickToneEventDetail;
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/ClickTone.d.ts
|
|
43
|
+
declare class ClickTone extends EventTarget {
|
|
44
|
+
#private;
|
|
45
|
+
constructor({
|
|
46
|
+
src,
|
|
47
|
+
volume,
|
|
48
|
+
muted,
|
|
49
|
+
throttle,
|
|
50
|
+
pitchVariation,
|
|
51
|
+
preload,
|
|
52
|
+
loop,
|
|
53
|
+
replay,
|
|
54
|
+
debug
|
|
55
|
+
}: ClickToneOptions);
|
|
56
|
+
static unlock(): void;
|
|
57
|
+
static get unlocked(): boolean;
|
|
58
|
+
get volume(): number;
|
|
59
|
+
get muted(): boolean;
|
|
60
|
+
get playing(): boolean;
|
|
61
|
+
preload(): Promise<AudioBuffer | undefined>;
|
|
62
|
+
unlock(): void;
|
|
63
|
+
setVolume(value: number): void;
|
|
64
|
+
setMuted(muted: boolean): void;
|
|
65
|
+
toggleMuted(): boolean;
|
|
66
|
+
play(input?: SoundInput | PlayOptions): Promise<void>;
|
|
67
|
+
stop(): void;
|
|
68
|
+
on<T extends ClickToneEventType>(type: T, listener: (detail: ClickToneEventDetail[T]) => void): () => void;
|
|
69
|
+
once<T extends ClickToneEventType>(type: T, listener: (detail: ClickToneEventDetail[T]) => void): void;
|
|
70
|
+
destroy(): void;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
export { ClickTone, type ClickToneEventDetail, type ClickToneEventType, type ClickToneOptions, type PlayOptions, type ReplayBehavior, type SoundDescriptor, type SoundInput, type SoundSource };
|
|
74
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
//#region src/constants.ts
|
|
2
|
+
const UNLOCK_EVENTS = [
|
|
3
|
+
"pointerdown",
|
|
4
|
+
"pointerup",
|
|
5
|
+
"touchstart",
|
|
6
|
+
"touchend",
|
|
7
|
+
"keydown"
|
|
8
|
+
];
|
|
9
|
+
const EXT_MIME = {
|
|
10
|
+
mp3: "audio/mpeg",
|
|
11
|
+
m4a: "audio/mp4",
|
|
12
|
+
mp4: "audio/mp4",
|
|
13
|
+
aac: "audio/aac",
|
|
14
|
+
oga: "audio/ogg",
|
|
15
|
+
ogg: "audio/ogg",
|
|
16
|
+
opus: "audio/ogg; codecs=opus",
|
|
17
|
+
wav: "audio/wav",
|
|
18
|
+
webm: "audio/webm",
|
|
19
|
+
flac: "audio/flac"
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/runtime.ts
|
|
24
|
+
const hasDOM = typeof window !== "undefined" && typeof document !== "undefined";
|
|
25
|
+
const noop = () => {};
|
|
26
|
+
/**
|
|
27
|
+
* iOS Safari (and desktop Safari) can leave an AudioContext in a "zombie"
|
|
28
|
+
* state after a tab switch / lock-screen return: `state === 'running'` yet no
|
|
29
|
+
* audio is produced. The only deterministic fix is recreating the context, but
|
|
30
|
+
* that cost is pointless on engines without the bug (e.g. desktop Chrome), so
|
|
31
|
+
* we gate the hard-recovery path behind this detection.
|
|
32
|
+
*/
|
|
33
|
+
const isAppleWebAudioFlaky = () => {
|
|
34
|
+
if (!hasDOM) return false;
|
|
35
|
+
const ua = navigator.userAgent;
|
|
36
|
+
const iOS = /iP(hone|ad|od)/.test(ua) || /Macintosh/.test(ua) && navigator.maxTouchPoints > 1;
|
|
37
|
+
const safari = /^((?!chrome|android|crios|fxios|edg).)*safari/i.test(ua);
|
|
38
|
+
return iOS || safari;
|
|
39
|
+
};
|
|
40
|
+
const clampVolume = (value) => {
|
|
41
|
+
if (!Number.isFinite(value) || value < 0) return 0;
|
|
42
|
+
return value > 1 ? 1 : value;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/engine/SharedAudioEngine.ts
|
|
47
|
+
/**
|
|
48
|
+
* One AudioContext shared by every ClickTone instance. iOS caps the number of
|
|
49
|
+
* concurrent AudioContexts, so a single context plus one set of gesture-unlock
|
|
50
|
+
* listeners is both cheaper and far more reliable than per-instance contexts.
|
|
51
|
+
*/
|
|
52
|
+
var SharedAudioEngine = class SharedAudioEngine {
|
|
53
|
+
static #ZOMBIE_PROBE_MS = 200;
|
|
54
|
+
#ctx = null;
|
|
55
|
+
#unlocked = false;
|
|
56
|
+
#primed = false;
|
|
57
|
+
#needsHardRecovery = false;
|
|
58
|
+
#probing = false;
|
|
59
|
+
#decodeCache = /* @__PURE__ */ new Map();
|
|
60
|
+
#onUnlock = /* @__PURE__ */ new Set();
|
|
61
|
+
#onRecreate = /* @__PURE__ */ new Set();
|
|
62
|
+
get unlocked() {
|
|
63
|
+
return this.#unlocked;
|
|
64
|
+
}
|
|
65
|
+
prime() {
|
|
66
|
+
if (this.#primed || !hasDOM) return;
|
|
67
|
+
this.#primed = true;
|
|
68
|
+
this.#installGestureUnlock();
|
|
69
|
+
this.#installVisibilityHandler();
|
|
70
|
+
}
|
|
71
|
+
context() {
|
|
72
|
+
if (this.#ctx || !hasDOM) return this.#ctx;
|
|
73
|
+
const Ctor = window.AudioContext ?? window.webkitAudioContext;
|
|
74
|
+
if (!Ctor) return null;
|
|
75
|
+
try {
|
|
76
|
+
this.#ctx = new Ctor({ latencyHint: "interactive" });
|
|
77
|
+
} catch {
|
|
78
|
+
this.#ctx = new Ctor();
|
|
79
|
+
}
|
|
80
|
+
return this.#ctx;
|
|
81
|
+
}
|
|
82
|
+
unlock() {
|
|
83
|
+
if (this.#needsHardRecovery) this.#recreate();
|
|
84
|
+
const ctx = this.context();
|
|
85
|
+
if (!ctx) return;
|
|
86
|
+
if (ctx.state === "running") {
|
|
87
|
+
if (this.#unlocked) this.#playSilentPing();
|
|
88
|
+
else this.#markUnlocked();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
ctx.resume().then(() => {
|
|
92
|
+
if (this.#unlocked) this.#playSilentPing();
|
|
93
|
+
else this.#markUnlocked();
|
|
94
|
+
}).catch(noop);
|
|
95
|
+
}
|
|
96
|
+
async ensureRunning() {
|
|
97
|
+
const ctx = this.context();
|
|
98
|
+
if (!ctx) return null;
|
|
99
|
+
const attempt = async () => {
|
|
100
|
+
if (this.#isRunning(ctx)) {
|
|
101
|
+
if (this.#unlocked) this.#playSilentPing();
|
|
102
|
+
else this.#markUnlocked();
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
await ctx.resume();
|
|
107
|
+
} catch {}
|
|
108
|
+
if (this.#isRunning(ctx)) {
|
|
109
|
+
if (this.#unlocked) this.#playSilentPing();
|
|
110
|
+
else this.#markUnlocked();
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
return false;
|
|
114
|
+
};
|
|
115
|
+
if (await attempt()) return ctx;
|
|
116
|
+
await new Promise((resolve) => setTimeout(resolve, 120));
|
|
117
|
+
if (await attempt()) return ctx;
|
|
118
|
+
await new Promise((resolve) => setTimeout(resolve, 600));
|
|
119
|
+
await attempt();
|
|
120
|
+
return ctx;
|
|
121
|
+
}
|
|
122
|
+
#isRunning(ctx) {
|
|
123
|
+
return ctx.state === "running";
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* After a lifecycle return, decide whether the context is genuinely dead and
|
|
127
|
+
* needs recreating, instead of recreating unconditionally. Runs in the
|
|
128
|
+
* background (no user gesture required) because it only reads state and
|
|
129
|
+
* `currentTime`:
|
|
130
|
+
*
|
|
131
|
+
* - A healthy context keeps advancing `currentTime` while `running`.
|
|
132
|
+
* - A zombie context reports `running` but `currentTime` stays frozen.
|
|
133
|
+
* - A context that cannot even reach `running` in the background needs a
|
|
134
|
+
* gesture-driven restart, which the recreate path provides safely.
|
|
135
|
+
*
|
|
136
|
+
* Recreation itself is deferred to the next user gesture via
|
|
137
|
+
* `#needsHardRecovery` (iOS refuses a full start outside a gesture).
|
|
138
|
+
*/
|
|
139
|
+
async #probeForZombie() {
|
|
140
|
+
if (this.#probing || this.#needsHardRecovery) return;
|
|
141
|
+
const ctx = this.#ctx;
|
|
142
|
+
if (!ctx || !this.#unlocked) return;
|
|
143
|
+
this.#probing = true;
|
|
144
|
+
try {
|
|
145
|
+
if (ctx.state !== "running") try {
|
|
146
|
+
await ctx.resume();
|
|
147
|
+
} catch {}
|
|
148
|
+
if (ctx.state !== "running") {
|
|
149
|
+
this.#needsHardRecovery = true;
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const start = ctx.currentTime;
|
|
153
|
+
await new Promise((resolve) => setTimeout(resolve, SharedAudioEngine.#ZOMBIE_PROBE_MS));
|
|
154
|
+
if (ctx.state === "running" && ctx.currentTime <= start) this.#needsHardRecovery = true;
|
|
155
|
+
} finally {
|
|
156
|
+
this.#probing = false;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Tear down the current (potentially zombie) AudioContext and build a fresh
|
|
161
|
+
* one. AudioBuffers are bound to a specific context, so the decode cache must
|
|
162
|
+
* be dropped; ClickTone#ensureGain rebinds its GainNode when the context
|
|
163
|
+
* changes. Must be called inside a user gesture.
|
|
164
|
+
*/
|
|
165
|
+
#recreate() {
|
|
166
|
+
this.#needsHardRecovery = false;
|
|
167
|
+
const old = this.#ctx;
|
|
168
|
+
this.#ctx = null;
|
|
169
|
+
this.#decodeCache.clear();
|
|
170
|
+
if (old) old.close().catch(noop);
|
|
171
|
+
const ctx = this.context();
|
|
172
|
+
if (!ctx) return;
|
|
173
|
+
[...this.#onRecreate].forEach((listener) => {
|
|
174
|
+
listener();
|
|
175
|
+
});
|
|
176
|
+
ctx.resume().then(() => this.#playSilentPing()).catch(noop);
|
|
177
|
+
}
|
|
178
|
+
onUnlock(listener) {
|
|
179
|
+
if (this.#unlocked) {
|
|
180
|
+
listener();
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
this.#onUnlock.add(listener);
|
|
184
|
+
}
|
|
185
|
+
onRecreate(listener) {
|
|
186
|
+
this.#onRecreate.add(listener);
|
|
187
|
+
return () => this.#onRecreate.delete(listener);
|
|
188
|
+
}
|
|
189
|
+
decode(url) {
|
|
190
|
+
const cached = this.#decodeCache.get(url);
|
|
191
|
+
if (cached) return cached;
|
|
192
|
+
const ctx = this.context();
|
|
193
|
+
if (!ctx) return Promise.reject(/* @__PURE__ */ new Error("Web Audio API is not available."));
|
|
194
|
+
const promise = (async () => {
|
|
195
|
+
const response = await fetch(url);
|
|
196
|
+
if (!response.ok) throw new Error(`Failed to fetch "${url}": ${response.status} ${response.statusText}`);
|
|
197
|
+
return ctx.decodeAudioData(await response.arrayBuffer());
|
|
198
|
+
})();
|
|
199
|
+
this.#decodeCache.set(url, promise);
|
|
200
|
+
promise.catch(() => this.#decodeCache.delete(url));
|
|
201
|
+
return promise;
|
|
202
|
+
}
|
|
203
|
+
#markUnlocked() {
|
|
204
|
+
if (this.#unlocked) return;
|
|
205
|
+
this.#unlocked = true;
|
|
206
|
+
this.#playSilentPing();
|
|
207
|
+
const listeners = [...this.#onUnlock];
|
|
208
|
+
this.#onUnlock.clear();
|
|
209
|
+
listeners.forEach((listener) => {
|
|
210
|
+
listener();
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
#playSilentPing() {
|
|
214
|
+
const ctx = this.#ctx;
|
|
215
|
+
if (!ctx) return;
|
|
216
|
+
try {
|
|
217
|
+
const buffer = ctx.createBuffer(1, 1, Math.max(22050, ctx.sampleRate));
|
|
218
|
+
const source = ctx.createBufferSource();
|
|
219
|
+
source.buffer = buffer;
|
|
220
|
+
const gain = ctx.createGain();
|
|
221
|
+
gain.gain.value = 1e-5;
|
|
222
|
+
source.connect(gain);
|
|
223
|
+
gain.connect(ctx.destination);
|
|
224
|
+
source.start(0);
|
|
225
|
+
source.stop(0);
|
|
226
|
+
} catch {}
|
|
227
|
+
}
|
|
228
|
+
#installGestureUnlock() {
|
|
229
|
+
const options = {
|
|
230
|
+
passive: true,
|
|
231
|
+
capture: true
|
|
232
|
+
};
|
|
233
|
+
const handler = () => this.unlock();
|
|
234
|
+
UNLOCK_EVENTS.forEach((event) => {
|
|
235
|
+
window.addEventListener(event, handler, options);
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
#installVisibilityHandler() {
|
|
239
|
+
const appleFlaky = isAppleWebAudioFlaky();
|
|
240
|
+
const wake = () => {
|
|
241
|
+
if (!this.#unlocked) return;
|
|
242
|
+
if (appleFlaky) {
|
|
243
|
+
this.#probeForZombie();
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
this.unlock();
|
|
247
|
+
setTimeout(() => this.unlock(), 120);
|
|
248
|
+
setTimeout(() => this.unlock(), 600);
|
|
249
|
+
};
|
|
250
|
+
const handler = () => {
|
|
251
|
+
if (document.hidden || !this.#unlocked) return;
|
|
252
|
+
wake();
|
|
253
|
+
};
|
|
254
|
+
document.addEventListener("visibilitychange", handler);
|
|
255
|
+
window.addEventListener("pageshow", wake);
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
const engine = new SharedAudioEngine();
|
|
259
|
+
|
|
260
|
+
//#endregion
|
|
261
|
+
//#region src/source.ts
|
|
262
|
+
const guessType = (url) => {
|
|
263
|
+
const clean = url.split(/[?#]/, 1)[0];
|
|
264
|
+
return EXT_MIME[clean.slice(clean.lastIndexOf(".") + 1).toLowerCase()];
|
|
265
|
+
};
|
|
266
|
+
const normalizeSource = (source) => {
|
|
267
|
+
if (typeof source === "string") return [{ src: source }];
|
|
268
|
+
if (source instanceof URL) return [{ src: source.href }];
|
|
269
|
+
if (hasDOM && source instanceof HTMLSourceElement) {
|
|
270
|
+
if (!source.src) throw new Error("<source> element has no \"src\" attribute.");
|
|
271
|
+
return [{
|
|
272
|
+
src: source.src,
|
|
273
|
+
type: source.type || void 0
|
|
274
|
+
}];
|
|
275
|
+
}
|
|
276
|
+
if (hasDOM && source instanceof HTMLAudioElement) {
|
|
277
|
+
const sources = Array.from(source.querySelectorAll("source")).filter((el) => el.src).map((el) => ({
|
|
278
|
+
src: el.src,
|
|
279
|
+
type: el.type || void 0
|
|
280
|
+
}));
|
|
281
|
+
if (sources.length) return sources;
|
|
282
|
+
if (source.src) return [{ src: source.src }];
|
|
283
|
+
throw new Error("<audio> element has no playable sources.");
|
|
284
|
+
}
|
|
285
|
+
if (typeof source === "object" && source !== null && "id" in source) {
|
|
286
|
+
if (!hasDOM) throw new Error("Cannot resolve element by id outside the DOM.");
|
|
287
|
+
const el = document.getElementById(String(source.id));
|
|
288
|
+
if (!el) throw new Error(`No element found with id "${source.id}".`);
|
|
289
|
+
if (el instanceof HTMLSourceElement || el instanceof HTMLAudioElement) return normalizeSource(el);
|
|
290
|
+
throw new Error(`Element with id "${source.id}" is not a <source> or <audio> element.`);
|
|
291
|
+
}
|
|
292
|
+
if (typeof source === "object" && source !== null && "src" in source) {
|
|
293
|
+
if (!source.src) throw new Error("Source descriptor has an empty \"src\".");
|
|
294
|
+
return [{
|
|
295
|
+
src: source.src,
|
|
296
|
+
type: source.type
|
|
297
|
+
}];
|
|
298
|
+
}
|
|
299
|
+
throw new Error("Invalid sound source.");
|
|
300
|
+
};
|
|
301
|
+
const resolveBestSource = (input) => {
|
|
302
|
+
const list = (Array.isArray(input) ? input : [input]).flatMap(normalizeSource);
|
|
303
|
+
if (!list.length) throw new Error("No sound source provided.");
|
|
304
|
+
if (list.length === 1 || !hasDOM) return list[0].src;
|
|
305
|
+
const probe = document.createElement("audio");
|
|
306
|
+
let maybe = null;
|
|
307
|
+
for (const item of list) {
|
|
308
|
+
const type = item.type ?? guessType(item.src);
|
|
309
|
+
if (!type) continue;
|
|
310
|
+
const verdict = probe.canPlayType(type);
|
|
311
|
+
if (verdict === "probably") return item.src;
|
|
312
|
+
if (verdict === "maybe" && maybe === null) maybe = item.src;
|
|
313
|
+
}
|
|
314
|
+
return maybe ?? list[0].src;
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/ClickTone.ts
|
|
319
|
+
var ClickTone = class extends EventTarget {
|
|
320
|
+
#url = null;
|
|
321
|
+
#initError = null;
|
|
322
|
+
#volume;
|
|
323
|
+
#muted;
|
|
324
|
+
#throttle;
|
|
325
|
+
#pitch;
|
|
326
|
+
#loop;
|
|
327
|
+
#replay;
|
|
328
|
+
#debug;
|
|
329
|
+
#lastPlay = 0;
|
|
330
|
+
#gain = null;
|
|
331
|
+
#activePlaybacks = /* @__PURE__ */ new Set();
|
|
332
|
+
#needsGainRefresh = false;
|
|
333
|
+
#visibilityHandler = null;
|
|
334
|
+
#recreateUnsubscribe = null;
|
|
335
|
+
#destroyed = false;
|
|
336
|
+
constructor({ src, volume = 1, muted = false, throttle = 0, pitchVariation = 0, preload = false, loop = false, replay = "overlap", debug = false }) {
|
|
337
|
+
super();
|
|
338
|
+
this.#volume = clampVolume(volume);
|
|
339
|
+
this.#muted = muted;
|
|
340
|
+
this.#throttle = Math.max(0, throttle);
|
|
341
|
+
this.#pitch = Math.min(1, Math.max(0, pitchVariation));
|
|
342
|
+
this.#loop = loop;
|
|
343
|
+
this.#replay = replay;
|
|
344
|
+
this.#debug = debug;
|
|
345
|
+
try {
|
|
346
|
+
this.#url = resolveBestSource(src);
|
|
347
|
+
} catch (error) {
|
|
348
|
+
this.#initError = error;
|
|
349
|
+
}
|
|
350
|
+
engine.prime();
|
|
351
|
+
engine.onUnlock(() => this.#emit("unlock"));
|
|
352
|
+
this.#recreateUnsubscribe = engine.onRecreate(() => this.#restartActiveLoops());
|
|
353
|
+
if (typeof document !== "undefined") {
|
|
354
|
+
this.#visibilityHandler = () => {
|
|
355
|
+
if (!document.hidden) this.#needsGainRefresh = true;
|
|
356
|
+
};
|
|
357
|
+
document.addEventListener("visibilitychange", this.#visibilityHandler);
|
|
358
|
+
}
|
|
359
|
+
if (preload) this.preload();
|
|
360
|
+
}
|
|
361
|
+
static unlock() {
|
|
362
|
+
engine.prime();
|
|
363
|
+
engine.unlock();
|
|
364
|
+
}
|
|
365
|
+
static get unlocked() {
|
|
366
|
+
return engine.unlocked;
|
|
367
|
+
}
|
|
368
|
+
get volume() {
|
|
369
|
+
return this.#volume;
|
|
370
|
+
}
|
|
371
|
+
get muted() {
|
|
372
|
+
return this.#muted;
|
|
373
|
+
}
|
|
374
|
+
get playing() {
|
|
375
|
+
return this.#activePlaybacks.size > 0;
|
|
376
|
+
}
|
|
377
|
+
async preload() {
|
|
378
|
+
if (this.#destroyed || !this.#url) return void 0;
|
|
379
|
+
try {
|
|
380
|
+
const buffer = await engine.decode(this.#url);
|
|
381
|
+
this.#emit("load", buffer);
|
|
382
|
+
return buffer;
|
|
383
|
+
} catch (error) {
|
|
384
|
+
this.#fail(error);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
unlock() {
|
|
389
|
+
engine.unlock();
|
|
390
|
+
}
|
|
391
|
+
setVolume(value) {
|
|
392
|
+
this.#volume = clampVolume(value);
|
|
393
|
+
if (this.#gain && !this.#muted) this.#rampGain(this.#volume);
|
|
394
|
+
}
|
|
395
|
+
setMuted(muted) {
|
|
396
|
+
this.#muted = muted;
|
|
397
|
+
if (this.#gain) this.#rampGain(muted ? 0 : this.#volume);
|
|
398
|
+
if (!muted) engine.unlock();
|
|
399
|
+
}
|
|
400
|
+
toggleMuted() {
|
|
401
|
+
this.setMuted(!this.#muted);
|
|
402
|
+
return this.#muted;
|
|
403
|
+
}
|
|
404
|
+
async play(input) {
|
|
405
|
+
await this.#play(this.#normalizePlayOptions(input));
|
|
406
|
+
}
|
|
407
|
+
stop() {
|
|
408
|
+
this.#stopActivePlaybacks(true);
|
|
409
|
+
}
|
|
410
|
+
async #play({ src, loop = this.#loop, replay = this.#replay }, { skipThrottle = false } = {}) {
|
|
411
|
+
if (this.#destroyed) return;
|
|
412
|
+
if (this.playing && replay === "ignore-if-playing") return;
|
|
413
|
+
const now = Date.now();
|
|
414
|
+
if (!skipThrottle && replay !== "restart" && now - this.#lastPlay < this.#throttle) return;
|
|
415
|
+
if (this.playing && (replay === "interrupt" || replay === "restart")) this.#stopActivePlaybacks(true);
|
|
416
|
+
this.#lastPlay = now;
|
|
417
|
+
engine.unlock();
|
|
418
|
+
let url;
|
|
419
|
+
try {
|
|
420
|
+
url = src ? resolveBestSource(src) : this.#requireUrl();
|
|
421
|
+
} catch (error) {
|
|
422
|
+
this.#fail(error);
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
try {
|
|
426
|
+
const ctx = await engine.ensureRunning();
|
|
427
|
+
if (!ctx || this.#destroyed) return;
|
|
428
|
+
if (ctx.state !== "running") throw new Error("AudioContext is not running.");
|
|
429
|
+
const buffer = await engine.decode(url);
|
|
430
|
+
if (ctx.state !== "running") await ctx.resume().catch(noop);
|
|
431
|
+
const gain = this.#ensureGain(ctx);
|
|
432
|
+
const source = ctx.createBufferSource();
|
|
433
|
+
source.buffer = buffer;
|
|
434
|
+
source.loop = loop;
|
|
435
|
+
if (this.#pitch > 0) source.playbackRate.value = Math.max(.5, 1 + (Math.random() * 2 - 1) * this.#pitch);
|
|
436
|
+
source.connect(gain);
|
|
437
|
+
const playback = {
|
|
438
|
+
source,
|
|
439
|
+
url,
|
|
440
|
+
loop,
|
|
441
|
+
stopped: false
|
|
442
|
+
};
|
|
443
|
+
this.#activePlaybacks.add(playback);
|
|
444
|
+
const ended = new Promise((resolve) => {
|
|
445
|
+
source.onended = () => {
|
|
446
|
+
this.#finishPlayback(playback, !playback.stopped);
|
|
447
|
+
resolve();
|
|
448
|
+
};
|
|
449
|
+
});
|
|
450
|
+
source.start(0);
|
|
451
|
+
this.#emit("play");
|
|
452
|
+
if (!loop) await ended;
|
|
453
|
+
} catch (error) {
|
|
454
|
+
this.#fail(error);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
on(type, listener) {
|
|
458
|
+
const handler = (event) => listener(event.detail);
|
|
459
|
+
this.addEventListener(type, handler);
|
|
460
|
+
return () => this.removeEventListener(type, handler);
|
|
461
|
+
}
|
|
462
|
+
once(type, listener) {
|
|
463
|
+
const handler = (event) => listener(event.detail);
|
|
464
|
+
this.addEventListener(type, handler, { once: true });
|
|
465
|
+
}
|
|
466
|
+
destroy() {
|
|
467
|
+
if (this.#destroyed) return;
|
|
468
|
+
this.#destroyed = true;
|
|
469
|
+
this.#stopActivePlaybacks(false);
|
|
470
|
+
if (this.#visibilityHandler && typeof document !== "undefined") {
|
|
471
|
+
document.removeEventListener("visibilitychange", this.#visibilityHandler);
|
|
472
|
+
this.#visibilityHandler = null;
|
|
473
|
+
}
|
|
474
|
+
this.#recreateUnsubscribe?.();
|
|
475
|
+
this.#recreateUnsubscribe = null;
|
|
476
|
+
this.#gain?.disconnect();
|
|
477
|
+
this.#gain = null;
|
|
478
|
+
}
|
|
479
|
+
#normalizePlayOptions(input) {
|
|
480
|
+
if (this.#isPlayOptions(input)) return input;
|
|
481
|
+
return { src: input };
|
|
482
|
+
}
|
|
483
|
+
#isPlayOptions(input) {
|
|
484
|
+
return typeof input === "object" && input !== null && ("loop" in input || "replay" in input);
|
|
485
|
+
}
|
|
486
|
+
#stopActivePlaybacks(emitStop) {
|
|
487
|
+
const playbacks = [...this.#activePlaybacks];
|
|
488
|
+
if (!playbacks.length) return;
|
|
489
|
+
playbacks.forEach((playback) => {
|
|
490
|
+
playback.stopped = true;
|
|
491
|
+
try {
|
|
492
|
+
playback.source.stop(0);
|
|
493
|
+
} catch {}
|
|
494
|
+
this.#finishPlayback(playback, false);
|
|
495
|
+
});
|
|
496
|
+
if (emitStop) this.#emit("stop");
|
|
497
|
+
}
|
|
498
|
+
#finishPlayback(playback, emitEnd) {
|
|
499
|
+
if (!this.#activePlaybacks.delete(playback)) return;
|
|
500
|
+
try {
|
|
501
|
+
playback.source.disconnect();
|
|
502
|
+
} catch {}
|
|
503
|
+
if (emitEnd) this.#emit("end");
|
|
504
|
+
}
|
|
505
|
+
#restartActiveLoops() {
|
|
506
|
+
if (this.#destroyed) return;
|
|
507
|
+
const loopUrls = [...this.#activePlaybacks].filter((playback) => playback.loop).map((playback) => playback.url);
|
|
508
|
+
if (!loopUrls.length) return;
|
|
509
|
+
this.#stopActivePlaybacks(false);
|
|
510
|
+
loopUrls.forEach((src) => {
|
|
511
|
+
this.#play({
|
|
512
|
+
src,
|
|
513
|
+
loop: true,
|
|
514
|
+
replay: "overlap"
|
|
515
|
+
}, { skipThrottle: true });
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
#requireUrl() {
|
|
519
|
+
if (this.#url) return this.#url;
|
|
520
|
+
throw this.#initError ?? /* @__PURE__ */ new Error("No valid sound source.");
|
|
521
|
+
}
|
|
522
|
+
#ensureGain(ctx) {
|
|
523
|
+
if (!this.#gain || this.#gain.context !== ctx) {
|
|
524
|
+
this.#gain = ctx.createGain();
|
|
525
|
+
this.#gain.gain.value = this.#muted ? 0 : this.#volume;
|
|
526
|
+
this.#gain.connect(ctx.destination);
|
|
527
|
+
this.#needsGainRefresh = false;
|
|
528
|
+
} else if (this.#needsGainRefresh) {
|
|
529
|
+
this.#gain.disconnect();
|
|
530
|
+
this.#gain.connect(ctx.destination);
|
|
531
|
+
this.#needsGainRefresh = false;
|
|
532
|
+
}
|
|
533
|
+
return this.#gain;
|
|
534
|
+
}
|
|
535
|
+
#rampGain(target) {
|
|
536
|
+
const gain = this.#gain;
|
|
537
|
+
if (!gain) return;
|
|
538
|
+
const now = gain.context.currentTime;
|
|
539
|
+
gain.gain.cancelScheduledValues(now);
|
|
540
|
+
gain.gain.setValueAtTime(gain.gain.value, now);
|
|
541
|
+
gain.gain.linearRampToValueAtTime(target, now + .015);
|
|
542
|
+
}
|
|
543
|
+
#emit(type, detail) {
|
|
544
|
+
if (typeof CustomEvent !== "undefined") this.dispatchEvent(new CustomEvent(type, { detail }));
|
|
545
|
+
else if (typeof Event !== "undefined") {
|
|
546
|
+
const event = new Event(type);
|
|
547
|
+
event.detail = detail;
|
|
548
|
+
this.dispatchEvent(event);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
#fail(error) {
|
|
552
|
+
if (this.#debug) console.error("[ClickTone]", error);
|
|
553
|
+
this.#emit("error", error);
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
//#endregion
|
|
558
|
+
export { ClickTone };
|
|
559
|
+
//# sourceMappingURL=index.js.map
|