clicktone 2.0.0-dev.0 → 2.0.0
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 +3 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.es.js +221 -157
- package/dist/index.umd.js +1 -1
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -4,9 +4,11 @@ A lightweight helper for UI sound feedback. It wraps the Web Audio API with a ti
|
|
|
4
4
|
|
|
5
5
|
- Single shared `AudioContext` for every instance (no iOS context-limit issues).
|
|
6
6
|
- Reliable autoplay unlock: eager gesture listeners, synchronous resume, silent priming ping, re-resume on `visibilitychange`.
|
|
7
|
+
- Self-healing on iOS/Safari: detects a "zombie" context after tab/app switch or lock-screen and transparently rebuilds it on the next interaction.
|
|
7
8
|
- Automatic format fallback via `canPlayType` (great for Safari, which dislikes OGG/Opus).
|
|
8
9
|
- Shared decode cache, throttling, volume control, and subtle pitch variation.
|
|
9
10
|
- Event-based (`EventTarget`) with a typed `on()` / `once()` API; `play()` also returns a `Promise`.
|
|
11
|
+
- [Demo](https://codepen.io/ux-ui/pen/yLwbmMr)
|
|
10
12
|
|
|
11
13
|
## Install
|
|
12
14
|
|
|
@@ -103,6 +105,7 @@ Mobile browsers (especially Safari on iOS) block audio until the user interacts
|
|
|
103
105
|
- One shared `AudioContext` (with `latencyHint: 'interactive'`) — one unlock unlocks every instance.
|
|
104
106
|
- Global gesture listeners (`pointerdown` / `pointerup` / `touchstart` / `touchend` / `keydown`) resume the context on the first interaction anywhere on the page.
|
|
105
107
|
- A silent priming ping is played right after unlock, and the context is re-resumed on `visibilitychange`.
|
|
108
|
+
- 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.
|
|
106
109
|
- Decoded buffers are cached and shared, so the first click is not delayed by the network.
|
|
107
110
|
|
|
108
111
|
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.
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var w=["pointerdown","pointerup","touchstart","touchend","keydown"],p={mp3:"audio/mpeg",m4a:"audio/mp4",mp4:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",webm:"audio/webm",flac:"audio/flac"},c=typeof window<"u"&&typeof document<"u",u=()=>{},y=()=>{if(!c)return!1;const e=navigator.userAgent,t=/iP(hone|ad|od)/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,i=/^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);return t||i},l=e=>!Number.isFinite(e)||e<0?0:e>1?1:e,g=class f{static#a=200;#i=null;#t=!1;#n=!1;#s=!1;#c=!1;#u=new Map;#l=new Set;get unlocked(){return this.#t}prime(){this.#n||!c||(this.#n=!0,this.#w(),this.#m())}context(){if(this.#i||!c)return this.#i;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#i=new t({latencyHint:"interactive"})}catch{this.#i=new t}return this.#i}unlock(){this.#s&&this.#h();const t=this.context();if(t){if(t.state==="running"){this.#t?this.#o():this.#r();return}t.resume().then(()=>{this.#t?this.#o():this.#r()}).catch(u)}}async ensureRunning(){const t=this.context();if(!t)return null;const i=async()=>{if(this.#e(t))return this.#t?this.#o():this.#r(),!0;try{await t.resume()}catch{}return this.#e(t)?(this.#t?this.#o():this.#r(),!0):!1};return await i()||(await new Promise(n=>setTimeout(n,120)),await i())||(await new Promise(n=>setTimeout(n,600)),await i()),t}#e(t){return t.state==="running"}async#d(){if(this.#c||this.#s)return;const t=this.#i;if(!(!t||!this.#t)){this.#c=!0;try{if(t.state!=="running")try{await t.resume()}catch{}if(t.state!=="running"){this.#s=!0;return}const i=t.currentTime;await new Promise(n=>setTimeout(n,f.#a)),t.state==="running"&&t.currentTime<=i&&(this.#s=!0)}finally{this.#c=!1}}}#h(){this.#s=!1;const t=this.#i;this.#i=null,this.#u.clear(),t&&t.close().catch(u);const i=this.context();i&&i.resume().then(()=>this.#o()).catch(u)}onUnlock(t){if(this.#t){t();return}this.#l.add(t)}decode(t){const i=this.#u.get(t);if(i)return i;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const r=(async()=>{const s=await fetch(t);if(!s.ok)throw new Error(`Failed to fetch "${t}": ${s.status} ${s.statusText}`);return n.decodeAudioData(await s.arrayBuffer())})();return this.#u.set(t,r),r.catch(()=>this.#u.delete(t)),r}#r(){if(this.#t)return;this.#t=!0,this.#o();const t=[...this.#l];this.#l.clear(),t.forEach(i=>{i()})}#o(){const t=this.#i;if(t)try{const i=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=i;const r=t.createGain();r.gain.value=1e-5,n.connect(r),r.connect(t.destination),n.start(0),n.stop(0)}catch{}}#w(){const t={passive:!0,capture:!0},i=()=>this.unlock();w.forEach(n=>{window.addEventListener(n,i,t)})}#m(){const t=y(),i=()=>{if(this.#t){if(t){this.#d();return}this.unlock(),setTimeout(()=>this.unlock(),120),setTimeout(()=>this.unlock(),600)}},n=()=>{document.hidden||!this.#t||i()};document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",i)}},a=new g,v=e=>{const t=e.split(/[?#]/,1)[0];return p[t.slice(t.lastIndexOf(".")+1).toLowerCase()]},m=e=>{if(typeof e=="string")return[{src:e}];if(e instanceof URL)return[{src:e.href}];if(c&&e instanceof HTMLSourceElement){if(!e.src)throw new Error('<source> element has no "src" attribute.');return[{src:e.src,type:e.type||void 0}]}if(c&&e instanceof HTMLAudioElement){const t=Array.from(e.querySelectorAll("source")).filter(i=>i.src).map(i=>({src:i.src,type:i.type||void 0}));if(t.length)return t;if(e.src)return[{src:e.src}];throw new Error("<audio> element has no playable sources.")}if(typeof e=="object"&&e!==null&&"id"in e){if(!c)throw new Error("Cannot resolve element by id outside the DOM.");const t=document.getElementById(String(e.id));if(!t)throw new Error(`No element found with id "${e.id}".`);if(t instanceof HTMLSourceElement||t instanceof HTMLAudioElement)return m(t);throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`)}if(typeof e=="object"&&e!==null&&"src"in e){if(!e.src)throw new Error('Source descriptor has an empty "src".');return[{src:e.src,type:e.type}]}throw new Error("Invalid sound source.")},d=e=>{const t=(Array.isArray(e)?e:[e]).flatMap(m);if(!t.length)throw new Error("No sound source provided.");if(t.length===1||!c)return t[0].src;const i=document.createElement("audio");let n=null;for(const r of t){const s=r.type??v(r.src);if(!s)continue;const o=i.canPlayType(s);if(o==="probably")return r.src;o==="maybe"&&n===null&&(n=r.src)}return n??t[0].src},E=class extends EventTarget{#a=null;#i=null;#t;#n;#s;#c;#u;#l=0;#e=null;#d=!1;#h=null;#r=!1;constructor({src:e,volume:t=1,muted:i=!1,throttle:n=0,pitchVariation:r=0,preload:s=!1,debug:o=!1}){super(),this.#t=l(t),this.#n=i,this.#s=Math.max(0,n),this.#c=Math.min(1,Math.max(0,r)),this.#u=o;try{this.#a=d(e)}catch(h){this.#i=h}a.prime(),a.onUnlock(()=>this.#f("unlock")),typeof document<"u"&&(this.#h=()=>{document.hidden||(this.#d=!0)},document.addEventListener("visibilitychange",this.#h)),s&&this.preload()}static unlock(){a.prime(),a.unlock()}static get unlocked(){return a.unlocked}get volume(){return this.#t}get muted(){return this.#n}async preload(){if(!(this.#r||!this.#a))try{const e=await a.decode(this.#a);return this.#f("load",e),e}catch(e){this.#p(e);return}}unlock(){a.unlock()}setVolume(e){this.#t=l(e),this.#e&&!this.#n&&this.#m(this.#t)}setMuted(e){this.#n=e,this.#e&&this.#m(e?0:this.#t),e||a.unlock()}toggleMuted(){return this.setMuted(!this.#n),this.#n}async play(e){if(this.#r)return;const t=Date.now();if(t-this.#l<this.#s)return;this.#l=t,a.unlock();let i;try{i=e?d(e):this.#o()}catch(n){this.#p(n);return}try{const n=await a.ensureRunning();if(!n||this.#r)return;if(n.state!=="running")throw new Error("AudioContext is not running.");const r=await a.decode(i);n.state!=="running"&&await n.resume().catch(u);const s=this.#w(n),o=n.createBufferSource();o.buffer=r,this.#c>0&&(o.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#c)),o.connect(s),this.#f("play"),await new Promise(h=>{o.onended=()=>{o.disconnect(),h()},o.start(0)}),this.#f("end")}catch(n){this.#p(n)}}on(e,t){const i=n=>t(n.detail);return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}once(e,t){const i=n=>t(n.detail);this.addEventListener(e,i,{once:!0})}destroy(){this.#r||(this.#r=!0,this.#h&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.#h),this.#h=null),this.#e?.disconnect(),this.#e=null)}#o(){if(this.#a)return this.#a;throw this.#i??new Error("No valid sound source.")}#w(e){return!this.#e||this.#e.context!==e?(this.#e=e.createGain(),this.#e.gain.value=this.#n?0:this.#t,this.#e.connect(e.destination),this.#d=!1):this.#d&&(this.#e.disconnect(),this.#e.connect(e.destination),this.#d=!1),this.#e}#m(e){const t=this.#e;if(!t)return;const i=t.context.currentTime;t.gain.cancelScheduledValues(i),t.gain.setValueAtTime(t.gain.value,i),t.gain.linearRampToValueAtTime(e,i+.015)}#f(e,t){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(e,{detail:t}));else if(typeof Event<"u"){const i=new Event(e);i.detail=t,this.dispatchEvent(i)}}#p(e){this.#u,this.#f("error",e)}};exports.ClickTone=E;
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export * from './main'
|
|
1
|
+
export * from './main.js'
|
|
2
2
|
export {}
|
package/dist/index.es.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var w = [
|
|
2
2
|
"pointerdown",
|
|
3
3
|
"pointerup",
|
|
4
4
|
"touchstart",
|
|
@@ -15,266 +15,330 @@ var l = [
|
|
|
15
15
|
wav: "audio/wav",
|
|
16
16
|
webm: "audio/webm",
|
|
17
17
|
flac: "audio/flac"
|
|
18
|
-
}, c = typeof window < "u" && typeof document < "u",
|
|
19
|
-
},
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
#a =
|
|
25
|
-
#
|
|
18
|
+
}, c = typeof window < "u" && typeof document < "u", h = () => {
|
|
19
|
+
}, y = () => {
|
|
20
|
+
if (!c) return !1;
|
|
21
|
+
const e = navigator.userAgent, t = /iP(hone|ad|od)/.test(e) || navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1, i = /^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);
|
|
22
|
+
return t || i;
|
|
23
|
+
}, l = (e) => !Number.isFinite(e) || e < 0 ? 0 : e > 1 ? 1 : e, g = class f {
|
|
24
|
+
static #a = 200;
|
|
25
|
+
#i = null;
|
|
26
|
+
#t = !1;
|
|
27
|
+
#n = !1;
|
|
28
|
+
#s = !1;
|
|
29
|
+
#c = !1;
|
|
30
|
+
#h = /* @__PURE__ */ new Map();
|
|
31
|
+
#l = /* @__PURE__ */ new Set();
|
|
26
32
|
get unlocked() {
|
|
27
|
-
return this.#
|
|
33
|
+
return this.#t;
|
|
28
34
|
}
|
|
29
35
|
prime() {
|
|
30
|
-
this.#
|
|
36
|
+
this.#n || !c || (this.#n = !0, this.#w(), this.#m());
|
|
31
37
|
}
|
|
32
38
|
context() {
|
|
33
|
-
if (this.#
|
|
39
|
+
if (this.#i || !c) return this.#i;
|
|
34
40
|
const t = window.AudioContext ?? window.webkitAudioContext;
|
|
35
41
|
if (!t) return null;
|
|
36
42
|
try {
|
|
37
|
-
this.#
|
|
43
|
+
this.#i = new t({ latencyHint: "interactive" });
|
|
38
44
|
} catch {
|
|
39
|
-
this.#
|
|
45
|
+
this.#i = new t();
|
|
40
46
|
}
|
|
41
|
-
return this.#
|
|
47
|
+
return this.#i;
|
|
42
48
|
}
|
|
43
49
|
unlock() {
|
|
50
|
+
this.#s && this.#u();
|
|
44
51
|
const t = this.context();
|
|
45
52
|
if (t) {
|
|
46
53
|
if (t.state === "running") {
|
|
47
|
-
this.#
|
|
54
|
+
this.#t ? this.#o() : this.#r();
|
|
48
55
|
return;
|
|
49
56
|
}
|
|
50
|
-
t.resume().then(() =>
|
|
57
|
+
t.resume().then(() => {
|
|
58
|
+
this.#t ? this.#o() : this.#r();
|
|
59
|
+
}).catch(h);
|
|
51
60
|
}
|
|
52
61
|
}
|
|
62
|
+
async ensureRunning() {
|
|
63
|
+
const t = this.context();
|
|
64
|
+
if (!t) return null;
|
|
65
|
+
const i = async () => {
|
|
66
|
+
if (this.#e(t))
|
|
67
|
+
return this.#t ? this.#o() : this.#r(), !0;
|
|
68
|
+
try {
|
|
69
|
+
await t.resume();
|
|
70
|
+
} catch {
|
|
71
|
+
}
|
|
72
|
+
return this.#e(t) ? (this.#t ? this.#o() : this.#r(), !0) : !1;
|
|
73
|
+
};
|
|
74
|
+
return await i() || (await new Promise((n) => setTimeout(n, 120)), await i()) || (await new Promise((n) => setTimeout(n, 600)), await i()), t;
|
|
75
|
+
}
|
|
76
|
+
#e(t) {
|
|
77
|
+
return t.state === "running";
|
|
78
|
+
}
|
|
79
|
+
async #d() {
|
|
80
|
+
if (this.#c || this.#s) return;
|
|
81
|
+
const t = this.#i;
|
|
82
|
+
if (!(!t || !this.#t)) {
|
|
83
|
+
this.#c = !0;
|
|
84
|
+
try {
|
|
85
|
+
if (t.state !== "running") try {
|
|
86
|
+
await t.resume();
|
|
87
|
+
} catch {
|
|
88
|
+
}
|
|
89
|
+
if (t.state !== "running") {
|
|
90
|
+
this.#s = !0;
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const i = t.currentTime;
|
|
94
|
+
await new Promise((n) => setTimeout(n, f.#a)), t.state === "running" && t.currentTime <= i && (this.#s = !0);
|
|
95
|
+
} finally {
|
|
96
|
+
this.#c = !1;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
#u() {
|
|
101
|
+
this.#s = !1;
|
|
102
|
+
const t = this.#i;
|
|
103
|
+
this.#i = null, this.#h.clear(), t && t.close().catch(h);
|
|
104
|
+
const i = this.context();
|
|
105
|
+
i && i.resume().then(() => this.#o()).catch(h);
|
|
106
|
+
}
|
|
53
107
|
onUnlock(t) {
|
|
54
|
-
if (this.#
|
|
108
|
+
if (this.#t) {
|
|
55
109
|
t();
|
|
56
110
|
return;
|
|
57
111
|
}
|
|
58
|
-
this.#
|
|
112
|
+
this.#l.add(t);
|
|
59
113
|
}
|
|
60
114
|
decode(t) {
|
|
61
|
-
const
|
|
62
|
-
if (
|
|
115
|
+
const i = this.#h.get(t);
|
|
116
|
+
if (i) return i;
|
|
63
117
|
const n = this.context();
|
|
64
118
|
if (!n) return Promise.reject(/* @__PURE__ */ new Error("Web Audio API is not available."));
|
|
65
119
|
const r = (async () => {
|
|
66
|
-
const
|
|
67
|
-
if (!
|
|
68
|
-
return n.decodeAudioData(await
|
|
120
|
+
const s = await fetch(t);
|
|
121
|
+
if (!s.ok) throw new Error(`Failed to fetch "${t}": ${s.status} ${s.statusText}`);
|
|
122
|
+
return n.decodeAudioData(await s.arrayBuffer());
|
|
69
123
|
})();
|
|
70
|
-
return this.#
|
|
71
|
-
}
|
|
72
|
-
#
|
|
73
|
-
if (this.#
|
|
74
|
-
this.#
|
|
75
|
-
const t = [...this.#
|
|
76
|
-
this.#
|
|
77
|
-
|
|
124
|
+
return this.#h.set(t, r), r.catch(() => this.#h.delete(t)), r;
|
|
125
|
+
}
|
|
126
|
+
#r() {
|
|
127
|
+
if (this.#t) return;
|
|
128
|
+
this.#t = !0, this.#o();
|
|
129
|
+
const t = [...this.#l];
|
|
130
|
+
this.#l.clear(), t.forEach((i) => {
|
|
131
|
+
i();
|
|
78
132
|
});
|
|
79
133
|
}
|
|
80
|
-
#
|
|
81
|
-
const t = this.#
|
|
134
|
+
#o() {
|
|
135
|
+
const t = this.#i;
|
|
82
136
|
if (t)
|
|
83
137
|
try {
|
|
84
|
-
const
|
|
85
|
-
n.buffer =
|
|
138
|
+
const i = t.createBuffer(1, 1, Math.max(22050, t.sampleRate)), n = t.createBufferSource();
|
|
139
|
+
n.buffer = i;
|
|
86
140
|
const r = t.createGain();
|
|
87
141
|
r.gain.value = 1e-5, n.connect(r), r.connect(t.destination), n.start(0), n.stop(0);
|
|
88
142
|
} catch {
|
|
89
143
|
}
|
|
90
144
|
}
|
|
91
|
-
#
|
|
145
|
+
#w() {
|
|
92
146
|
const t = {
|
|
93
147
|
passive: !0,
|
|
94
148
|
capture: !0
|
|
95
|
-
},
|
|
96
|
-
|
|
97
|
-
window.addEventListener(n,
|
|
98
|
-
})
|
|
99
|
-
l.forEach((n) => {
|
|
100
|
-
window.removeEventListener(n, e, t);
|
|
101
|
-
});
|
|
102
|
-
};
|
|
149
|
+
}, i = () => this.unlock();
|
|
150
|
+
w.forEach((n) => {
|
|
151
|
+
window.addEventListener(n, i, t);
|
|
152
|
+
});
|
|
103
153
|
}
|
|
104
|
-
#
|
|
105
|
-
const t = () => {
|
|
106
|
-
|
|
154
|
+
#m() {
|
|
155
|
+
const t = y(), i = () => {
|
|
156
|
+
if (this.#t) {
|
|
157
|
+
if (t) {
|
|
158
|
+
this.#d();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
this.unlock(), setTimeout(() => this.unlock(), 120), setTimeout(() => this.unlock(), 600);
|
|
162
|
+
}
|
|
163
|
+
}, n = () => {
|
|
164
|
+
document.hidden || !this.#t || i();
|
|
107
165
|
};
|
|
108
|
-
document.addEventListener("visibilitychange",
|
|
109
|
-
}
|
|
110
|
-
},
|
|
111
|
-
const
|
|
112
|
-
return p[
|
|
113
|
-
}, m = (
|
|
114
|
-
if (typeof
|
|
115
|
-
if (
|
|
116
|
-
if (c &&
|
|
117
|
-
if (!
|
|
166
|
+
document.addEventListener("visibilitychange", n), window.addEventListener("pageshow", i);
|
|
167
|
+
}
|
|
168
|
+
}, a = new g(), v = (e) => {
|
|
169
|
+
const t = e.split(/[?#]/, 1)[0];
|
|
170
|
+
return p[t.slice(t.lastIndexOf(".") + 1).toLowerCase()];
|
|
171
|
+
}, m = (e) => {
|
|
172
|
+
if (typeof e == "string") return [{ src: e }];
|
|
173
|
+
if (e instanceof URL) return [{ src: e.href }];
|
|
174
|
+
if (c && e instanceof HTMLSourceElement) {
|
|
175
|
+
if (!e.src) throw new Error('<source> element has no "src" attribute.');
|
|
118
176
|
return [{
|
|
119
|
-
src:
|
|
120
|
-
type:
|
|
177
|
+
src: e.src,
|
|
178
|
+
type: e.type || void 0
|
|
121
179
|
}];
|
|
122
180
|
}
|
|
123
|
-
if (c &&
|
|
124
|
-
const
|
|
125
|
-
src:
|
|
126
|
-
type:
|
|
181
|
+
if (c && e instanceof HTMLAudioElement) {
|
|
182
|
+
const t = Array.from(e.querySelectorAll("source")).filter((i) => i.src).map((i) => ({
|
|
183
|
+
src: i.src,
|
|
184
|
+
type: i.type || void 0
|
|
127
185
|
}));
|
|
128
|
-
if (
|
|
129
|
-
if (
|
|
186
|
+
if (t.length) return t;
|
|
187
|
+
if (e.src) return [{ src: e.src }];
|
|
130
188
|
throw new Error("<audio> element has no playable sources.");
|
|
131
189
|
}
|
|
132
|
-
if (typeof
|
|
190
|
+
if (typeof e == "object" && e !== null && "id" in e) {
|
|
133
191
|
if (!c) throw new Error("Cannot resolve element by id outside the DOM.");
|
|
134
|
-
const
|
|
135
|
-
if (!
|
|
136
|
-
if (
|
|
137
|
-
throw new Error(`Element with id "${
|
|
192
|
+
const t = document.getElementById(String(e.id));
|
|
193
|
+
if (!t) throw new Error(`No element found with id "${e.id}".`);
|
|
194
|
+
if (t instanceof HTMLSourceElement || t instanceof HTMLAudioElement) return m(t);
|
|
195
|
+
throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`);
|
|
138
196
|
}
|
|
139
|
-
if (typeof
|
|
140
|
-
if (!
|
|
197
|
+
if (typeof e == "object" && e !== null && "src" in e) {
|
|
198
|
+
if (!e.src) throw new Error('Source descriptor has an empty "src".');
|
|
141
199
|
return [{
|
|
142
|
-
src:
|
|
143
|
-
type:
|
|
200
|
+
src: e.src,
|
|
201
|
+
type: e.type
|
|
144
202
|
}];
|
|
145
203
|
}
|
|
146
204
|
throw new Error("Invalid sound source.");
|
|
147
|
-
},
|
|
148
|
-
const
|
|
149
|
-
if (!
|
|
150
|
-
if (
|
|
151
|
-
const
|
|
152
|
-
let
|
|
153
|
-
for (const
|
|
154
|
-
const
|
|
155
|
-
if (!
|
|
156
|
-
const
|
|
157
|
-
if (
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
return
|
|
161
|
-
},
|
|
162
|
-
#
|
|
205
|
+
}, d = (e) => {
|
|
206
|
+
const t = (Array.isArray(e) ? e : [e]).flatMap(m);
|
|
207
|
+
if (!t.length) throw new Error("No sound source provided.");
|
|
208
|
+
if (t.length === 1 || !c) return t[0].src;
|
|
209
|
+
const i = document.createElement("audio");
|
|
210
|
+
let n = null;
|
|
211
|
+
for (const r of t) {
|
|
212
|
+
const s = r.type ?? v(r.src);
|
|
213
|
+
if (!s) continue;
|
|
214
|
+
const o = i.canPlayType(s);
|
|
215
|
+
if (o === "probably") return r.src;
|
|
216
|
+
o === "maybe" && n === null && (n = r.src);
|
|
217
|
+
}
|
|
218
|
+
return n ?? t[0].src;
|
|
219
|
+
}, E = class extends EventTarget {
|
|
220
|
+
#a = null;
|
|
163
221
|
#i = null;
|
|
164
|
-
#
|
|
222
|
+
#t;
|
|
165
223
|
#n;
|
|
166
|
-
#a;
|
|
167
224
|
#s;
|
|
168
225
|
#c;
|
|
169
|
-
#
|
|
226
|
+
#h;
|
|
227
|
+
#l = 0;
|
|
170
228
|
#e = null;
|
|
171
|
-
#
|
|
172
|
-
|
|
173
|
-
|
|
229
|
+
#d = !1;
|
|
230
|
+
#u = null;
|
|
231
|
+
#r = !1;
|
|
232
|
+
constructor({ src: e, volume: t = 1, muted: i = !1, throttle: n = 0, pitchVariation: r = 0, preload: s = !1, debug: o = !1 }) {
|
|
233
|
+
super(), this.#t = l(t), this.#n = i, this.#s = Math.max(0, n), this.#c = Math.min(1, Math.max(0, r)), this.#h = o;
|
|
174
234
|
try {
|
|
175
|
-
this.#
|
|
176
|
-
} catch (
|
|
177
|
-
this.#i =
|
|
235
|
+
this.#a = d(e);
|
|
236
|
+
} catch (u) {
|
|
237
|
+
this.#i = u;
|
|
178
238
|
}
|
|
179
|
-
|
|
239
|
+
a.prime(), a.onUnlock(() => this.#f("unlock")), typeof document < "u" && (this.#u = () => {
|
|
240
|
+
document.hidden || (this.#d = !0);
|
|
241
|
+
}, document.addEventListener("visibilitychange", this.#u)), s && this.preload();
|
|
180
242
|
}
|
|
181
243
|
static unlock() {
|
|
182
|
-
|
|
244
|
+
a.prime(), a.unlock();
|
|
183
245
|
}
|
|
184
246
|
static get unlocked() {
|
|
185
|
-
return
|
|
247
|
+
return a.unlocked;
|
|
186
248
|
}
|
|
187
249
|
get volume() {
|
|
188
|
-
return this.#
|
|
250
|
+
return this.#t;
|
|
189
251
|
}
|
|
190
252
|
get muted() {
|
|
191
253
|
return this.#n;
|
|
192
254
|
}
|
|
193
255
|
async preload() {
|
|
194
|
-
if (!(this.#
|
|
256
|
+
if (!(this.#r || !this.#a))
|
|
195
257
|
try {
|
|
196
|
-
const
|
|
197
|
-
return this.#
|
|
198
|
-
} catch (
|
|
199
|
-
this.#
|
|
258
|
+
const e = await a.decode(this.#a);
|
|
259
|
+
return this.#f("load", e), e;
|
|
260
|
+
} catch (e) {
|
|
261
|
+
this.#p(e);
|
|
200
262
|
return;
|
|
201
263
|
}
|
|
202
264
|
}
|
|
203
265
|
unlock() {
|
|
204
|
-
|
|
266
|
+
a.unlock();
|
|
205
267
|
}
|
|
206
|
-
setVolume(
|
|
207
|
-
this.#
|
|
268
|
+
setVolume(e) {
|
|
269
|
+
this.#t = l(e), this.#e && !this.#n && this.#m(this.#t);
|
|
208
270
|
}
|
|
209
|
-
setMuted(
|
|
210
|
-
this.#n =
|
|
271
|
+
setMuted(e) {
|
|
272
|
+
this.#n = e, this.#e && this.#m(e ? 0 : this.#t), e || a.unlock();
|
|
211
273
|
}
|
|
212
274
|
toggleMuted() {
|
|
213
275
|
return this.setMuted(!this.#n), this.#n;
|
|
214
276
|
}
|
|
215
|
-
async play(
|
|
216
|
-
if (this.#
|
|
217
|
-
const
|
|
218
|
-
if (
|
|
219
|
-
this.#
|
|
220
|
-
let
|
|
277
|
+
async play(e) {
|
|
278
|
+
if (this.#r) return;
|
|
279
|
+
const t = Date.now();
|
|
280
|
+
if (t - this.#l < this.#s) return;
|
|
281
|
+
this.#l = t, a.unlock();
|
|
282
|
+
let i;
|
|
221
283
|
try {
|
|
222
|
-
|
|
223
|
-
} catch (
|
|
224
|
-
this.#
|
|
284
|
+
i = e ? d(e) : this.#o();
|
|
285
|
+
} catch (n) {
|
|
286
|
+
this.#p(n);
|
|
225
287
|
return;
|
|
226
288
|
}
|
|
227
289
|
try {
|
|
228
|
-
const
|
|
229
|
-
if (!
|
|
230
|
-
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
this.#
|
|
290
|
+
const n = await a.ensureRunning();
|
|
291
|
+
if (!n || this.#r) return;
|
|
292
|
+
if (n.state !== "running") throw new Error("AudioContext is not running.");
|
|
293
|
+
const r = await a.decode(i);
|
|
294
|
+
n.state !== "running" && await n.resume().catch(h);
|
|
295
|
+
const s = this.#w(n), o = n.createBufferSource();
|
|
296
|
+
o.buffer = r, this.#c > 0 && (o.playbackRate.value = Math.max(0.5, 1 + (Math.random() * 2 - 1) * this.#c)), o.connect(s), this.#f("play"), await new Promise((u) => {
|
|
297
|
+
o.onended = () => {
|
|
298
|
+
o.disconnect(), u();
|
|
299
|
+
}, o.start(0);
|
|
300
|
+
}), this.#f("end");
|
|
301
|
+
} catch (n) {
|
|
302
|
+
this.#p(n);
|
|
239
303
|
}
|
|
240
304
|
}
|
|
241
|
-
on(
|
|
242
|
-
const
|
|
243
|
-
return this.addEventListener(
|
|
305
|
+
on(e, t) {
|
|
306
|
+
const i = (n) => t(n.detail);
|
|
307
|
+
return this.addEventListener(e, i), () => this.removeEventListener(e, i);
|
|
244
308
|
}
|
|
245
|
-
once(
|
|
246
|
-
const
|
|
247
|
-
this.addEventListener(
|
|
309
|
+
once(e, t) {
|
|
310
|
+
const i = (n) => t(n.detail);
|
|
311
|
+
this.addEventListener(e, i, { once: !0 });
|
|
248
312
|
}
|
|
249
313
|
destroy() {
|
|
250
|
-
this.#
|
|
314
|
+
this.#r || (this.#r = !0, this.#u && typeof document < "u" && (document.removeEventListener("visibilitychange", this.#u), this.#u = null), this.#e?.disconnect(), this.#e = null);
|
|
251
315
|
}
|
|
252
|
-
#
|
|
253
|
-
if (this.#
|
|
316
|
+
#o() {
|
|
317
|
+
if (this.#a) return this.#a;
|
|
254
318
|
throw this.#i ?? /* @__PURE__ */ new Error("No valid sound source.");
|
|
255
319
|
}
|
|
256
|
-
#
|
|
257
|
-
return
|
|
320
|
+
#w(e) {
|
|
321
|
+
return !this.#e || this.#e.context !== e ? (this.#e = e.createGain(), this.#e.gain.value = this.#n ? 0 : this.#t, this.#e.connect(e.destination), this.#d = !1) : this.#d && (this.#e.disconnect(), this.#e.connect(e.destination), this.#d = !1), this.#e;
|
|
258
322
|
}
|
|
259
|
-
#
|
|
260
|
-
const
|
|
261
|
-
if (!
|
|
262
|
-
const
|
|
263
|
-
|
|
323
|
+
#m(e) {
|
|
324
|
+
const t = this.#e;
|
|
325
|
+
if (!t) return;
|
|
326
|
+
const i = t.context.currentTime;
|
|
327
|
+
t.gain.cancelScheduledValues(i), t.gain.setValueAtTime(t.gain.value, i), t.gain.linearRampToValueAtTime(e, i + 0.015);
|
|
264
328
|
}
|
|
265
|
-
#
|
|
266
|
-
if (typeof CustomEvent < "u") this.dispatchEvent(new CustomEvent(
|
|
329
|
+
#f(e, t) {
|
|
330
|
+
if (typeof CustomEvent < "u") this.dispatchEvent(new CustomEvent(e, { detail: t }));
|
|
267
331
|
else if (typeof Event < "u") {
|
|
268
|
-
const
|
|
269
|
-
|
|
332
|
+
const i = new Event(e);
|
|
333
|
+
i.detail = t, this.dispatchEvent(i);
|
|
270
334
|
}
|
|
271
335
|
}
|
|
272
|
-
#
|
|
273
|
-
this.#
|
|
336
|
+
#p(e) {
|
|
337
|
+
this.#h, this.#f("error", e);
|
|
274
338
|
}
|
|
275
339
|
};
|
|
276
340
|
export {
|
|
277
|
-
|
|
341
|
+
E as ClickTone
|
|
278
342
|
};
|
|
279
343
|
|
|
280
344
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.umd.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(u,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(u=typeof globalThis<"u"?globalThis:u||self,h(u.ClickTone={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var h=["pointerdown","pointerup","touchstart","touchend","keydown"],y={mp3:"audio/mpeg",m4a:"audio/mp4",mp4:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",webm:"audio/webm",flac:"audio/flac"},c=typeof window<"u"&&typeof document<"u",l=()=>{},g=()=>{if(!c)return!1;const e=navigator.userAgent,t=/iP(hone|ad|od)/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,i=/^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);return t||i},f=e=>!Number.isFinite(e)||e<0?0:e>1?1:e,v=class w{static#a=200;#i=null;#t=!1;#n=!1;#s=!1;#c=!1;#u=new Map;#l=new Set;get unlocked(){return this.#t}prime(){this.#n||!c||(this.#n=!0,this.#p(),this.#m())}context(){if(this.#i||!c)return this.#i;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#i=new t({latencyHint:"interactive"})}catch{this.#i=new t}return this.#i}unlock(){this.#s&&this.#h();const t=this.context();if(t){if(t.state==="running"){this.#t?this.#o():this.#r();return}t.resume().then(()=>{this.#t?this.#o():this.#r()}).catch(l)}}async ensureRunning(){const t=this.context();if(!t)return null;const i=async()=>{if(this.#e(t))return this.#t?this.#o():this.#r(),!0;try{await t.resume()}catch{}return this.#e(t)?(this.#t?this.#o():this.#r(),!0):!1};return await i()||(await new Promise(n=>setTimeout(n,120)),await i())||(await new Promise(n=>setTimeout(n,600)),await i()),t}#e(t){return t.state==="running"}async#d(){if(this.#c||this.#s)return;const t=this.#i;if(!(!t||!this.#t)){this.#c=!0;try{if(t.state!=="running")try{await t.resume()}catch{}if(t.state!=="running"){this.#s=!0;return}const i=t.currentTime;await new Promise(n=>setTimeout(n,w.#a)),t.state==="running"&&t.currentTime<=i&&(this.#s=!0)}finally{this.#c=!1}}}#h(){this.#s=!1;const t=this.#i;this.#i=null,this.#u.clear(),t&&t.close().catch(l);const i=this.context();i&&i.resume().then(()=>this.#o()).catch(l)}onUnlock(t){if(this.#t){t();return}this.#l.add(t)}decode(t){const i=this.#u.get(t);if(i)return i;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const r=(async()=>{const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch "${t}": ${o.status} ${o.statusText}`);return n.decodeAudioData(await o.arrayBuffer())})();return this.#u.set(t,r),r.catch(()=>this.#u.delete(t)),r}#r(){if(this.#t)return;this.#t=!0,this.#o();const t=[...this.#l];this.#l.clear(),t.forEach(i=>{i()})}#o(){const t=this.#i;if(t)try{const i=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=i;const r=t.createGain();r.gain.value=1e-5,n.connect(r),r.connect(t.destination),n.start(0),n.stop(0)}catch{}}#p(){const t={passive:!0,capture:!0},i=()=>this.unlock();h.forEach(n=>{window.addEventListener(n,i,t)})}#m(){const t=g(),i=()=>{if(this.#t){if(t){this.#d();return}this.unlock(),setTimeout(()=>this.unlock(),120),setTimeout(()=>this.unlock(),600)}},n=()=>{document.hidden||!this.#t||i()};document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",i)}},s=new v,E=e=>{const t=e.split(/[?#]/,1)[0];return y[t.slice(t.lastIndexOf(".")+1).toLowerCase()]},m=e=>{if(typeof e=="string")return[{src:e}];if(e instanceof URL)return[{src:e.href}];if(c&&e instanceof HTMLSourceElement){if(!e.src)throw new Error('<source> element has no "src" attribute.');return[{src:e.src,type:e.type||void 0}]}if(c&&e instanceof HTMLAudioElement){const t=Array.from(e.querySelectorAll("source")).filter(i=>i.src).map(i=>({src:i.src,type:i.type||void 0}));if(t.length)return t;if(e.src)return[{src:e.src}];throw new Error("<audio> element has no playable sources.")}if(typeof e=="object"&&e!==null&&"id"in e){if(!c)throw new Error("Cannot resolve element by id outside the DOM.");const t=document.getElementById(String(e.id));if(!t)throw new Error(`No element found with id "${e.id}".`);if(t instanceof HTMLSourceElement||t instanceof HTMLAudioElement)return m(t);throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`)}if(typeof e=="object"&&e!==null&&"src"in e){if(!e.src)throw new Error('Source descriptor has an empty "src".');return[{src:e.src,type:e.type}]}throw new Error("Invalid sound source.")},p=e=>{const t=(Array.isArray(e)?e:[e]).flatMap(m);if(!t.length)throw new Error("No sound source provided.");if(t.length===1||!c)return t[0].src;const i=document.createElement("audio");let n=null;for(const r of t){const o=r.type??E(r.src);if(!o)continue;const a=i.canPlayType(o);if(a==="probably")return r.src;a==="maybe"&&n===null&&(n=r.src)}return n??t[0].src},b=class extends EventTarget{#a=null;#i=null;#t;#n;#s;#c;#u;#l=0;#e=null;#d=!1;#h=null;#r=!1;constructor({src:e,volume:t=1,muted:i=!1,throttle:n=0,pitchVariation:r=0,preload:o=!1,debug:a=!1}){super(),this.#t=f(t),this.#n=i,this.#s=Math.max(0,n),this.#c=Math.min(1,Math.max(0,r)),this.#u=a;try{this.#a=p(e)}catch(d){this.#i=d}s.prime(),s.onUnlock(()=>this.#f("unlock")),typeof document<"u"&&(this.#h=()=>{document.hidden||(this.#d=!0)},document.addEventListener("visibilitychange",this.#h)),o&&this.preload()}static unlock(){s.prime(),s.unlock()}static get unlocked(){return s.unlocked}get volume(){return this.#t}get muted(){return this.#n}async preload(){if(!(this.#r||!this.#a))try{const e=await s.decode(this.#a);return this.#f("load",e),e}catch(e){this.#w(e);return}}unlock(){s.unlock()}setVolume(e){this.#t=f(e),this.#e&&!this.#n&&this.#m(this.#t)}setMuted(e){this.#n=e,this.#e&&this.#m(e?0:this.#t),e||s.unlock()}toggleMuted(){return this.setMuted(!this.#n),this.#n}async play(e){if(this.#r)return;const t=Date.now();if(t-this.#l<this.#s)return;this.#l=t,s.unlock();let i;try{i=e?p(e):this.#o()}catch(n){this.#w(n);return}try{const n=await s.ensureRunning();if(!n||this.#r)return;if(n.state!=="running")throw new Error("AudioContext is not running.");const r=await s.decode(i);n.state!=="running"&&await n.resume().catch(l);const o=this.#p(n),a=n.createBufferSource();a.buffer=r,this.#c>0&&(a.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#c)),a.connect(o),this.#f("play"),await new Promise(d=>{a.onended=()=>{a.disconnect(),d()},a.start(0)}),this.#f("end")}catch(n){this.#w(n)}}on(e,t){const i=n=>t(n.detail);return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}once(e,t){const i=n=>t(n.detail);this.addEventListener(e,i,{once:!0})}destroy(){this.#r||(this.#r=!0,this.#h&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.#h),this.#h=null),this.#e?.disconnect(),this.#e=null)}#o(){if(this.#a)return this.#a;throw this.#i??new Error("No valid sound source.")}#p(e){return!this.#e||this.#e.context!==e?(this.#e=e.createGain(),this.#e.gain.value=this.#n?0:this.#t,this.#e.connect(e.destination),this.#d=!1):this.#d&&(this.#e.disconnect(),this.#e.connect(e.destination),this.#d=!1),this.#e}#m(e){const t=this.#e;if(!t)return;const i=t.context.currentTime;t.gain.cancelScheduledValues(i),t.gain.setValueAtTime(t.gain.value,i),t.gain.linearRampToValueAtTime(e,i+.015)}#f(e,t){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(e,{detail:t}));else if(typeof Event<"u"){const i=new Event(e);i.detail=t,this.dispatchEvent(i)}}#w(e){this.#u,this.#f("error",e)}};u.ClickTone=b});
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=index.umd.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clicktone",
|
|
3
|
-
"version": "2.0.0
|
|
3
|
+
"version": "2.0.0",
|
|
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",
|
|
@@ -54,15 +54,15 @@
|
|
|
54
54
|
"LICENSE"
|
|
55
55
|
],
|
|
56
56
|
"devDependencies": {
|
|
57
|
-
"@biomejs/biome": "2.4.
|
|
58
|
-
"@types/node": "25.
|
|
57
|
+
"@biomejs/biome": "2.4.16",
|
|
58
|
+
"@types/node": "25.9.1",
|
|
59
59
|
"esbuild": "0.28.0",
|
|
60
|
-
"jsdom": "
|
|
60
|
+
"jsdom": "29.1.1",
|
|
61
61
|
"rimraf": "6.1.3",
|
|
62
62
|
"typescript": "6.0.3",
|
|
63
|
-
"vite": "8.0.
|
|
64
|
-
"vite-plugin-dts": "5.0.
|
|
65
|
-
"vitest": "
|
|
63
|
+
"vite": "8.0.16",
|
|
64
|
+
"vite-plugin-dts": "5.0.2",
|
|
65
|
+
"vitest": "4.1.8"
|
|
66
66
|
},
|
|
67
67
|
"keywords": [
|
|
68
68
|
"MP3",
|