clicktone 1.7.1 → 1.8.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 CHANGED
@@ -9,8 +9,8 @@
9
9
 
10
10
  </div>
11
11
 
12
- <p align="center">ClickTone is designed to control audio playback with various settings, including volume control, callback and debug mode. It also includes iOS support.</p>
13
- <p align="center"><sup>1kB gzipped</sup></p>
12
+ <p align="center">ClickTone is a lightweight helper for UI sound feedback. It wraps the Web Audio API, giving you instant click‑sounds with volume control, throttling, callbacks, and an iOS resume workaround.</p>
13
+ <p align="center"><sup>1.2kB gzipped</sup></p>
14
14
  <p align="center"><a href="https://codepen.io/ux-ui/pen/yLwbmMr">Demo</a></p>
15
15
  <br>
16
16
 
@@ -31,32 +31,43 @@ import ClickTone from 'clicktone';
31
31
 
32
32
  &#10148; **Usage**
33
33
 
34
- <sub>ClickTone uses the Web Audio API, which supports many audio file formats: MP3, WAV, OGG, AAC and others. Note that not all browsers support these formats.</sub>
34
+ ```html
35
+ <audio preload="auto">
36
+ <source id="click-source" src="./click.mp3" type="audio/mpeg" />
37
+ <source src="./click.ogg" type="audio/ogg" />
38
+ </audio>
39
+ ```
40
+
35
41
  ```javascript
36
42
  const sound = new ClickTone({
37
- file: './sound.mp3',
43
+ // Any of the forms work:
44
+ // file: './sound.mp3',
38
45
  // file: new URL('./sound.mp3', import.meta.url).href,
46
+ // file: document.querySelector('#click-source') as HTMLSourceElement,
47
+ file: { id: 'click-source' },
48
+
39
49
  volume: 0.7,
40
50
  throttle: 100,
41
- callback: () => { console.log('Playback ended') },
51
+ callback: () => console.log('done'),
42
52
  debug: true,
43
53
  });
44
54
 
45
- const play = () => sound.play();
46
-
47
- button.addEventListener('pointerdown', play);
55
+ button.addEventListener('click', () => click.play());
48
56
  ```
57
+ <sup>ClickTone uses the Web Audio API, which supports many audio file formats: MP3, WAV, OGG, AAC and others. Note that not all browsers support these formats.</sup>
49
58
  <br>
59
+ <sup>Tip: you can also override the source at call‑time: click.play('./alt.wav').</sup>
60
+ <br><br>
50
61
 
51
62
  &#10148; **Options**
52
63
 
53
- | Option | Type | Default | Description |
54
- |:----------:|:-----------------------------------:|:--------:|:---------------------------------------------------------------------------------------------|
55
- | `file` | `string` | `none` | The URL of the audio file to be played. |
56
- | `volume` | `number` | `1.0` | Volume level for the audio playback, ranging from 0.0 (mute) to 1.0 (full volume). |
57
- | `callback` | `((error?: Error) => void) \| null` | `null` | A callback function to be executed after the audio finishes playing, or if an error occurs. |
58
- | `throttle` | `number` | `0` | Minimum time (in milliseconds) between successive audio plays to prevent rapid repeat plays. |
59
- | `debug` | `boolean` | `false` | If `true`, debug information and errors will be logged to the console. |
64
+ | Option | Type | Default | Description |
65
+ |:----------:|:-----------------------------------------------:|:-------:|:--------------------------------------------------------------------------------------------------------------------------------|
66
+ | `file` | `string \| HTMLSourceElement \| { id: string }` | – | Audio source. Either a direct URL, an actual `<source>` element, or an object whose id maps to a `<source>` already in the DOM. |
67
+ | `volume` | `number` | `1` | Playback volume `0`–`1`. |
68
+ | `callback` | `((error?: Error) => void) \| null` | `null` | Called after playback ends or if an error occurs. |
69
+ | `throttle` | `number` | `0` | Debounce interval in ms. Playback requests arriving sooner are ignored. |
70
+ | `debug` | `boolean` | `false` | Log internal errors/warnings to the console. |
60
71
  <br>
61
72
 
62
73
  &#10148; **License**
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var h=(t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i;var o=(t,e,i)=>h(t,typeof e!="symbol"?e+"":e,i);module.exports=class{constructor({file:t,volume:e=1,callback:i=null,throttle:a=0,debug:n=!1}){o(this,"file");o(this,"volume");o(this,"callback");o(this,"throttle");o(this,"debug");o(this,"lastClickTime");o(this,"audioCache");o(this,"audioContext");this.file=t,this.volume=e,this.callback=i,this.throttle=a,this.debug=n,this.lastClickTime=0,this.audioCache={},this.audioContext=null}initAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.iOSFixAudioContext())}iOSFixAudioContext(){if(this.audioContext&&this.audioContext.state==="suspended"&&"ontouchstart"in window){const t=()=>{this.audioContext.state==="suspended"&&this.audioContext.resume().then(()=>{document.body.removeEventListener("touchstart",t),document.body.removeEventListener("touchend",t)}).catch(e=>{this.debug})};document.body.addEventListener("touchstart",t,!1),document.body.addEventListener("touchend",t,!1)}}async fetchAndDecodeAudio(t){try{if(this.audioCache[t])return this.audioCache[t];const e=await fetch(t),i=await e.arrayBuffer(),a=await this.audioContext.decodeAudioData(i);return this.audioCache[t]=a,a}catch(e){throw this.debug,new Error(`Something went wrong when loading and decoding the audio: ${e.message}`)}}async playAudio(t){this.initAudioContext();try{const e=await this.fetchAndDecodeAudio(t),i=this.audioContext.createBufferSource(),a=this.audioContext.createGain();i.buffer=e,a.gain.value=this.volume,i.connect(a),a.connect(this.audioContext.destination),i.onended=()=>{this.callback&&this.callback()},i.start(0)}catch(e){throw this.debug,new Error(`Something went wrong while playing audio: ${e.message}`)}}throttleFn(t){return()=>{const e=Date.now();e-this.lastClickTime>=this.throttle&&(t().catch(i=>{this.debug}),this.lastClickTime=e)}}play(t=this.file){const e=this.throttleFn(()=>this.playAudio(t));try{e()}catch(i){if(this.debug,!this.callback)throw i;this.callback(i)}}};
1
+ "use strict";var s=Object.defineProperty;var a=(t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i;var n=(t,e,i)=>a(t,typeof e!="symbol"?e+"":e,i);module.exports=class{constructor({file:t,volume:e=1,callback:i=null,throttle:o=0,debug:r=!1}){n(this,"fileSource");n(this,"volume");n(this,"callback");n(this,"throttle");n(this,"debug");n(this,"lastClickTime");n(this,"audioCache");n(this,"audioContext");this.fileSource=t,this.volume=e,this.callback=i,this.throttle=o,this.debug=r,this.lastClickTime=0,this.audioCache={},this.audioContext=null}resolveFileUrl(t){if(typeof t=="string")return t;if(t instanceof HTMLSourceElement){if(!t.src)throw new Error('<source> element has no "src" attribute.');return t.src}if(typeof t=="object"&&t!==null&&"id"in t){const e=document.getElementById(String(t.id));if(!e)throw new Error(`No element found with id "${t.id}".`);if(!(e instanceof HTMLSourceElement))throw new Error(`Element with id "${t.id}" is not a <source> element.`);if(!e.src)throw new Error(`<source> element with id "${t.id}" has no "src" attribute.`);return e.src}throw new Error('Invalid "file" value. Expected string, HTMLSourceElement, or { id: string }.')}initAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.iOSFixAudioContext())}iOSFixAudioContext(){if(this.audioContext&&this.audioContext.state==="suspended"&&"ontouchstart"in window){const t=()=>{this.audioContext.state==="suspended"&&this.audioContext.resume().then(()=>{document.body.removeEventListener("touchstart",t),document.body.removeEventListener("touchend",t)}).catch(e=>{this.debug})};document.body.addEventListener("touchstart",t,!1),document.body.addEventListener("touchend",t,!1)}}async fetchAndDecodeAudio(t){try{if(this.audioCache[t])return this.audioCache[t];const e=await fetch(t),i=await e.arrayBuffer(),o=await this.audioContext.decodeAudioData(i);return this.audioCache[t]=o,o}catch(e){throw this.debug,new Error(`Something went wrong when loading and decoding the audio: ${e.message}`)}}async playAudio(t){this.initAudioContext();try{const e=await this.fetchAndDecodeAudio(t),i=this.audioContext.createBufferSource(),o=this.audioContext.createGain();i.buffer=e,o.gain.value=this.volume,i.connect(o),o.connect(this.audioContext.destination),i.onended=()=>{this.callback&&this.callback()},i.start(0)}catch(e){throw this.debug,new Error(`Something went wrong while playing audio: ${e.message}`)}}throttleFn(t){return()=>{const e=Date.now();e-this.lastClickTime>=this.throttle&&(t().catch(i=>{this.debug}),this.lastClickTime=e)}}play(t){let e;try{e=this.resolveFileUrl(t??this.fileSource)}catch(o){if(this.callback)return void this.callback(o);throw o}const i=this.throttleFn(()=>this.playAudio(e));try{i()}catch(o){if(this.debug,!this.callback)throw o;this.callback(o)}}};
package/dist/index.d.ts CHANGED
@@ -3,8 +3,11 @@ declare global {
3
3
  webkitAudioContext?: typeof AudioContext;
4
4
  }
5
5
  }
6
+ type FileSource = string | HTMLSourceElement | {
7
+ id: string;
8
+ };
6
9
  declare class ClickTone {
7
- private readonly file;
10
+ private readonly fileSource;
8
11
  private readonly volume;
9
12
  private readonly callback;
10
13
  private readonly throttle;
@@ -13,17 +16,18 @@ declare class ClickTone {
13
16
  private readonly audioCache;
14
17
  private audioContext;
15
18
  constructor({ file, volume, callback, throttle, debug, }: {
16
- file: string;
19
+ file: FileSource;
17
20
  volume?: number;
18
21
  callback?: ((error?: Error) => void) | null;
19
22
  throttle?: number;
20
23
  debug?: boolean;
21
24
  });
25
+ private resolveFileUrl;
22
26
  private initAudioContext;
23
27
  private iOSFixAudioContext;
24
28
  private fetchAndDecodeAudio;
25
29
  private playAudio;
26
30
  private throttleFn;
27
- play(url?: string): void;
31
+ play(file?: FileSource): void;
28
32
  }
29
33
  export default ClickTone;
package/dist/index.es.js CHANGED
@@ -1,17 +1,32 @@
1
- var d = Object.defineProperty;
2
- var h = (n, t, e) => t in n ? d(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var o = (n, t, e) => h(n, typeof t != "symbol" ? t + "" : t, e);
4
- class u {
5
- constructor({ file: t, volume: e = 1, callback: i = null, throttle: a = 0, debug: s = !1 }) {
6
- o(this, "file");
7
- o(this, "volume");
8
- o(this, "callback");
9
- o(this, "throttle");
10
- o(this, "debug");
11
- o(this, "lastClickTime");
12
- o(this, "audioCache");
13
- o(this, "audioContext");
14
- this.file = t, this.volume = e, this.callback = i, this.throttle = a, this.debug = s, this.lastClickTime = 0, this.audioCache = {}, this.audioContext = null;
1
+ var s = Object.defineProperty;
2
+ var c = (r, t, e) => t in r ? s(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
3
+ var n = (r, t, e) => c(r, typeof t != "symbol" ? t + "" : t, e);
4
+ class h {
5
+ constructor({ file: t, volume: e = 1, callback: o = null, throttle: i = 0, debug: a = !1 }) {
6
+ n(this, "fileSource");
7
+ n(this, "volume");
8
+ n(this, "callback");
9
+ n(this, "throttle");
10
+ n(this, "debug");
11
+ n(this, "lastClickTime");
12
+ n(this, "audioCache");
13
+ n(this, "audioContext");
14
+ this.fileSource = t, this.volume = e, this.callback = o, this.throttle = i, this.debug = a, this.lastClickTime = 0, this.audioCache = {}, this.audioContext = null;
15
+ }
16
+ resolveFileUrl(t) {
17
+ if (typeof t == "string") return t;
18
+ if (t instanceof HTMLSourceElement) {
19
+ if (!t.src) throw new Error('<source> element has no "src" attribute.');
20
+ return t.src;
21
+ }
22
+ if (typeof t == "object" && t !== null && "id" in t) {
23
+ const e = document.getElementById(String(t.id));
24
+ if (!e) throw new Error(`No element found with id "${t.id}".`);
25
+ if (!(e instanceof HTMLSourceElement)) throw new Error(`Element with id "${t.id}" is not a <source> element.`);
26
+ if (!e.src) throw new Error(`<source> element with id "${t.id}" has no "src" attribute.`);
27
+ return e.src;
28
+ }
29
+ throw new Error('Invalid "file" value. Expected string, HTMLSourceElement, or { id: string }.');
15
30
  }
16
31
  initAudioContext() {
17
32
  this.audioContext || (this.audioContext = new (window.AudioContext || window.webkitAudioContext)(), this.iOSFixAudioContext());
@@ -31,8 +46,8 @@ class u {
31
46
  async fetchAndDecodeAudio(t) {
32
47
  try {
33
48
  if (this.audioCache[t]) return this.audioCache[t];
34
- const e = await fetch(t), i = await e.arrayBuffer(), a = await this.audioContext.decodeAudioData(i);
35
- return this.audioCache[t] = a, a;
49
+ const e = await fetch(t), o = await e.arrayBuffer(), i = await this.audioContext.decodeAudioData(o);
50
+ return this.audioCache[t] = i, i;
36
51
  } catch (e) {
37
52
  throw this.debug, new Error(`Something went wrong when loading and decoding the audio: ${e.message}`);
38
53
  }
@@ -40,10 +55,10 @@ class u {
40
55
  async playAudio(t) {
41
56
  this.initAudioContext();
42
57
  try {
43
- const e = await this.fetchAndDecodeAudio(t), i = this.audioContext.createBufferSource(), a = this.audioContext.createGain();
44
- i.buffer = e, a.gain.value = this.volume, i.connect(a), a.connect(this.audioContext.destination), i.onended = () => {
58
+ const e = await this.fetchAndDecodeAudio(t), o = this.audioContext.createBufferSource(), i = this.audioContext.createGain();
59
+ o.buffer = e, i.gain.value = this.volume, o.connect(i), i.connect(this.audioContext.destination), o.onended = () => {
45
60
  this.callback && this.callback();
46
- }, i.start(0);
61
+ }, o.start(0);
47
62
  } catch (e) {
48
63
  throw this.debug, new Error(`Something went wrong while playing audio: ${e.message}`);
49
64
  }
@@ -51,15 +66,22 @@ class u {
51
66
  throttleFn(t) {
52
67
  return () => {
53
68
  const e = Date.now();
54
- e - this.lastClickTime >= this.throttle && (t().catch((i) => {
69
+ e - this.lastClickTime >= this.throttle && (t().catch((o) => {
55
70
  this.debug;
56
71
  }), this.lastClickTime = e);
57
72
  };
58
73
  }
59
- play(t = this.file) {
60
- const e = this.throttleFn(() => this.playAudio(t));
74
+ play(t) {
75
+ let e;
76
+ try {
77
+ e = this.resolveFileUrl(t ?? this.fileSource);
78
+ } catch (i) {
79
+ if (this.callback) return void this.callback(i);
80
+ throw i;
81
+ }
82
+ const o = this.throttleFn(() => this.playAudio(e));
61
83
  try {
62
- e();
84
+ o();
63
85
  } catch (i) {
64
86
  if (this.debug, !this.callback) throw i;
65
87
  this.callback(i);
@@ -67,5 +89,5 @@ class u {
67
89
  }
68
90
  }
69
91
  export {
70
- u as default
92
+ h as default
71
93
  };
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(e,t){typeof exports=="object"&&typeof module<"u"?module.exports=t():typeof define=="function"&&define.amd?define(t):(e=typeof globalThis<"u"?globalThis:e||self).ClickTone=t()})(this,function(){"use strict";var d=Object.defineProperty;var s=(e,t,i)=>t in e?d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var o=(e,t,i)=>s(e,typeof t!="symbol"?t+"":t,i);return class{constructor({file:e,volume:t=1,callback:i=null,throttle:n=0,debug:a=!1}){o(this,"file");o(this,"volume");o(this,"callback");o(this,"throttle");o(this,"debug");o(this,"lastClickTime");o(this,"audioCache");o(this,"audioContext");this.file=e,this.volume=t,this.callback=i,this.throttle=n,this.debug=a,this.lastClickTime=0,this.audioCache={},this.audioContext=null}initAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.iOSFixAudioContext())}iOSFixAudioContext(){if(this.audioContext&&this.audioContext.state==="suspended"&&"ontouchstart"in window){const e=()=>{this.audioContext.state==="suspended"&&this.audioContext.resume().then(()=>{document.body.removeEventListener("touchstart",e),document.body.removeEventListener("touchend",e)}).catch(t=>{this.debug})};document.body.addEventListener("touchstart",e,!1),document.body.addEventListener("touchend",e,!1)}}async fetchAndDecodeAudio(e){try{if(this.audioCache[e])return this.audioCache[e];const t=await fetch(e),i=await t.arrayBuffer(),n=await this.audioContext.decodeAudioData(i);return this.audioCache[e]=n,n}catch(t){throw this.debug,new Error(`Something went wrong when loading and decoding the audio: ${t.message}`)}}async playAudio(e){this.initAudioContext();try{const t=await this.fetchAndDecodeAudio(e),i=this.audioContext.createBufferSource(),n=this.audioContext.createGain();i.buffer=t,n.gain.value=this.volume,i.connect(n),n.connect(this.audioContext.destination),i.onended=()=>{this.callback&&this.callback()},i.start(0)}catch(t){throw this.debug,new Error(`Something went wrong while playing audio: ${t.message}`)}}throttleFn(e){return()=>{const t=Date.now();t-this.lastClickTime>=this.throttle&&(e().catch(i=>{this.debug}),this.lastClickTime=t)}}play(e=this.file){const t=this.throttleFn(()=>this.playAudio(e));try{t()}catch(i){if(this.debug,!this.callback)throw i;this.callback(i)}}}});
1
+ (function(t,e){typeof exports=="object"&&typeof module<"u"?module.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).ClickTone=e()})(this,function(){"use strict";var s=Object.defineProperty;var a=(t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i;var n=(t,e,i)=>a(t,typeof e!="symbol"?e+"":e,i);return class{constructor({file:t,volume:e=1,callback:i=null,throttle:o=0,debug:r=!1}){n(this,"fileSource");n(this,"volume");n(this,"callback");n(this,"throttle");n(this,"debug");n(this,"lastClickTime");n(this,"audioCache");n(this,"audioContext");this.fileSource=t,this.volume=e,this.callback=i,this.throttle=o,this.debug=r,this.lastClickTime=0,this.audioCache={},this.audioContext=null}resolveFileUrl(t){if(typeof t=="string")return t;if(t instanceof HTMLSourceElement){if(!t.src)throw new Error('<source> element has no "src" attribute.');return t.src}if(typeof t=="object"&&t!==null&&"id"in t){const e=document.getElementById(String(t.id));if(!e)throw new Error(`No element found with id "${t.id}".`);if(!(e instanceof HTMLSourceElement))throw new Error(`Element with id "${t.id}" is not a <source> element.`);if(!e.src)throw new Error(`<source> element with id "${t.id}" has no "src" attribute.`);return e.src}throw new Error('Invalid "file" value. Expected string, HTMLSourceElement, or { id: string }.')}initAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.iOSFixAudioContext())}iOSFixAudioContext(){if(this.audioContext&&this.audioContext.state==="suspended"&&"ontouchstart"in window){const t=()=>{this.audioContext.state==="suspended"&&this.audioContext.resume().then(()=>{document.body.removeEventListener("touchstart",t),document.body.removeEventListener("touchend",t)}).catch(e=>{this.debug})};document.body.addEventListener("touchstart",t,!1),document.body.addEventListener("touchend",t,!1)}}async fetchAndDecodeAudio(t){try{if(this.audioCache[t])return this.audioCache[t];const e=await fetch(t),i=await e.arrayBuffer(),o=await this.audioContext.decodeAudioData(i);return this.audioCache[t]=o,o}catch(e){throw this.debug,new Error(`Something went wrong when loading and decoding the audio: ${e.message}`)}}async playAudio(t){this.initAudioContext();try{const e=await this.fetchAndDecodeAudio(t),i=this.audioContext.createBufferSource(),o=this.audioContext.createGain();i.buffer=e,o.gain.value=this.volume,i.connect(o),o.connect(this.audioContext.destination),i.onended=()=>{this.callback&&this.callback()},i.start(0)}catch(e){throw this.debug,new Error(`Something went wrong while playing audio: ${e.message}`)}}throttleFn(t){return()=>{const e=Date.now();e-this.lastClickTime>=this.throttle&&(t().catch(i=>{this.debug}),this.lastClickTime=e)}}play(t){let e;try{e=this.resolveFileUrl(t??this.fileSource)}catch(o){if(this.callback)return void this.callback(o);throw o}const i=this.throttleFn(()=>this.playAudio(e));try{i()}catch(o){if(this.debug,!this.callback)throw o;this.callback(o)}}}});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "clicktone",
3
- "version": "1.7.1",
4
- "description": "ClickTone is designed to control audio playback with various settings, including volume control, callback and debug mode. It also includes iOS support.",
3
+ "version": "1.8.0",
4
+ "description": "ClickTone is a lightweight helper for UI sound feedback. It wraps the Web Audio API, giving you instant click‑sounds with volume control, throttling, callbacks, and an iOS resume workaround.",
5
5
  "author": "ux-ui.pro",
6
6
  "license": "MIT",
7
7
  "repository": {