clicktone 1.6.0 → 1.7.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 CHANGED
@@ -10,7 +10,7 @@
10
10
  </div>
11
11
 
12
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>850B gzipped</sup></p>
13
+ <p align="center"><sup>1kB 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
 
@@ -34,8 +34,8 @@ import ClickTone from 'clicktone';
34
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>
35
35
  ```javascript
36
36
  const sound = new ClickTone({
37
- // file: './sound.mp3',
38
- file: new URL('./sound.mp3', import.meta.url).href,
37
+ file: './sound.mp3',
38
+ // file: new URL('./sound.mp3', import.meta.url).href,
39
39
  volume: 0.7,
40
40
  throttle: 100,
41
41
  callback: () => { console.log('Playback ended') },
@@ -0,0 +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)}}};
@@ -0,0 +1,29 @@
1
+ declare global {
2
+ interface Window {
3
+ webkitAudioContext?: typeof AudioContext;
4
+ }
5
+ }
6
+ declare class ClickTone {
7
+ private readonly file;
8
+ private readonly volume;
9
+ private readonly callback;
10
+ private readonly throttle;
11
+ private readonly debug;
12
+ private lastClickTime;
13
+ private readonly audioCache;
14
+ private audioContext;
15
+ constructor({ file, volume, callback, throttle, debug, }: {
16
+ file: string;
17
+ volume?: number;
18
+ callback?: ((error?: Error) => void) | null;
19
+ throttle?: number;
20
+ debug?: boolean;
21
+ });
22
+ private initAudioContext;
23
+ private iOSFixAudioContext;
24
+ private fetchAndDecodeAudio;
25
+ private playAudio;
26
+ private throttleFn;
27
+ play(url?: string): void;
28
+ }
29
+ export default ClickTone;
@@ -0,0 +1,71 @@
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;
15
+ }
16
+ initAudioContext() {
17
+ this.audioContext || (this.audioContext = new (window.AudioContext || window.webkitAudioContext)(), this.iOSFixAudioContext());
18
+ }
19
+ iOSFixAudioContext() {
20
+ if (this.audioContext && this.audioContext.state === "suspended" && "ontouchstart" in window) {
21
+ const t = () => {
22
+ this.audioContext.state === "suspended" && this.audioContext.resume().then(() => {
23
+ document.body.removeEventListener("touchstart", t), document.body.removeEventListener("touchend", t);
24
+ }).catch((e) => {
25
+ this.debug;
26
+ });
27
+ };
28
+ document.body.addEventListener("touchstart", t, !1), document.body.addEventListener("touchend", t, !1);
29
+ }
30
+ }
31
+ async fetchAndDecodeAudio(t) {
32
+ try {
33
+ 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;
36
+ } catch (e) {
37
+ throw this.debug, new Error(`Something went wrong when loading and decoding the audio: ${e.message}`);
38
+ }
39
+ }
40
+ async playAudio(t) {
41
+ this.initAudioContext();
42
+ 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 = () => {
45
+ this.callback && this.callback();
46
+ }, i.start(0);
47
+ } catch (e) {
48
+ throw this.debug, new Error(`Something went wrong while playing audio: ${e.message}`);
49
+ }
50
+ }
51
+ throttleFn(t) {
52
+ return () => {
53
+ const e = Date.now();
54
+ e - this.lastClickTime >= this.throttle && (t().catch((i) => {
55
+ this.debug;
56
+ }), this.lastClickTime = e);
57
+ };
58
+ }
59
+ play(t = this.file) {
60
+ const e = this.throttleFn(() => this.playAudio(t));
61
+ try {
62
+ e();
63
+ } catch (i) {
64
+ if (this.debug, !this.callback) throw i;
65
+ this.callback(i);
66
+ }
67
+ }
68
+ }
69
+ export {
70
+ u as default
71
+ };
@@ -0,0 +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)}}}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clicktone",
3
- "version": "1.6.0",
3
+ "version": "1.7.1",
4
4
  "description": "ClickTone is designed to control audio playback with various settings, including volume control, callback and debug mode. It also includes iOS support.",
5
5
  "author": "ux-ui.pro",
6
6
  "license": "MIT",
@@ -14,32 +14,45 @@
14
14
  "homepage": "https://github.com/ux-ui-pro/clicktone",
15
15
  "sideEffects": false,
16
16
  "scripts": {
17
- "clean": "rm -rf dist .parcel-cache",
18
- "build": "yarn clean && parcel build",
19
- "lint:js": "eslint **/*.ts",
20
- "lint:fix:js": "eslint **/*.ts --fix",
21
- "format:js": "prettier --write **/*.ts",
17
+ "clean": "rimraf dist",
18
+ "build": "vite build",
19
+ "lint:js": "eslint src/**/*.{ts,js}",
20
+ "lint:fix:js": "eslint src/**/*.{ts,js} --fix",
21
+ "format:js": "prettier --write src/**/*.{ts,js}",
22
22
  "lint:fix": "yarn lint:fix:js && yarn format:js"
23
23
  },
24
- "browserslist": "> 0.5%, last 2 versions, not dead",
25
24
  "source": "src/index.ts",
26
- "main": "dist/index.js",
27
- "module": "dist/index.module.js",
28
- "types": "dist/clicktone.d.ts",
25
+ "main": "dist/index.cjs.js",
26
+ "module": "dist/index.es.js",
27
+ "browser": "./dist/index.umd.js",
28
+ "types": "dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "require": "./dist/index.cjs.js",
32
+ "import": "./dist/index.es.js",
33
+ "default": "./dist/index.umd.js"
34
+ },
35
+ "./dist/*": "./dist/*"
36
+ },
37
+ "files": [
38
+ "dist/"
39
+ ],
29
40
  "devDependencies": {
30
- "@eslint/js": "9.17.0",
31
- "@parcel/packager-ts": "2.13.3",
32
- "@parcel/transformer-typescript-types": "2.13.3",
33
- "@typescript-eslint/eslint-plugin": "8.18.2",
34
- "@typescript-eslint/parser": "8.18.2",
35
- "eslint": "9.17.0",
36
- "eslint-config-prettier": "9.1.0",
37
- "eslint-import-resolver-typescript": "3.7.0",
41
+ "@eslint/js": "9.22.0",
42
+ "@rollup/plugin-terser": "0.4.4",
43
+ "@types/node": "22.13.10",
44
+ "@typescript-eslint/eslint-plugin": "8.26.0",
45
+ "@typescript-eslint/parser": "8.26.0",
46
+ "eslint": "9.22.0",
47
+ "eslint-config-prettier": "10.1.1",
48
+ "eslint-import-resolver-typescript": "3.8.3",
38
49
  "eslint-plugin-import": "2.31.0",
39
- "globals": "15.14.0",
40
- "parcel": "2.13.3",
41
- "prettier": "3.4.2",
42
- "typescript": "5.7.2"
50
+ "globals": "16.0.0",
51
+ "prettier": "3.5.3",
52
+ "rimraf": "6.0.1",
53
+ "typescript": "5.8.2",
54
+ "vite": "6.2.1",
55
+ "vite-plugin-dts": "4.5.3"
43
56
  },
44
57
  "keywords": [
45
58
  "MP3",
package/.prettierignore DELETED
@@ -1,4 +0,0 @@
1
- node_modules
2
- dist
3
- .parcel
4
- .parcel-cache
package/.prettierrc.json DELETED
@@ -1,11 +0,0 @@
1
- {
2
- "semi": true,
3
- "singleQuote": true,
4
- "printWidth": 100,
5
- "trailingComma": "all",
6
- "arrowParens": "always",
7
- "tabWidth": 2,
8
- "useTabs": false,
9
- "bracketSpacing": true,
10
- "endOfLine": "lf"
11
- }
@@ -1,37 +0,0 @@
1
- # Contributor Covenant Code of Conduct
2
-
3
- ## Our Pledge
4
-
5
- In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, ethnicity, level of experience, nationality, personal appearance, race, or religion.
6
-
7
- ## Our Standards
8
-
9
- Examples of behavior that contributes to creating a positive environment include:
10
-
11
- * Using welcoming language
12
- * Being respectful of differing viewpoints and experiences
13
- * Gracefully accepting constructive criticism
14
- * Focusing on what is best for the community
15
-
16
- Examples of unacceptable behavior by participants include:
17
-
18
- * Trolling, insulting/derogatory comments, and personal or political attacks
19
- * Public or private harassment
20
- * Publishing others' private information, such as a physical or electronic address, without explicit permission
21
- * Other conduct which could reasonably be considered inappropriate in a professional setting
22
-
23
- ## Our Responsibilities
24
-
25
- Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
26
-
27
- Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
28
-
29
- ## Scope
30
-
31
- This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
32
-
33
- ## Enforcement
34
-
35
- Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident.
36
-
37
- Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
@@ -1,18 +0,0 @@
1
- declare global {
2
- interface Window {
3
- webkitAudioContext?: typeof AudioContext;
4
- }
5
- }
6
- export default class ClickTone {
7
- constructor({ file, volume, callback, throttle, debug, }: {
8
- file: string;
9
- volume?: number;
10
- callback?: ((error?: Error) => void) | null;
11
- throttle?: number;
12
- debug?: boolean;
13
- });
14
- play(url?: string): void;
15
- }
16
- export default ClickTone;
17
-
18
- //# sourceMappingURL=clicktone.d.ts.map
@@ -1 +0,0 @@
1
- {"mappings":"AAAA,QAAQ,MAAM,CAAC;IACb,UAAU,MAAM;QACd,kBAAkB,CAAC,EAAE,OAAO,YAAY,CAAC;KAC1C;CACF;AAED,qBAAM,SAAS;gBAUD,EACV,IAAI,EACJ,MAAY,EACZ,QAAe,EACf,QAAY,EACZ,KAAa,GACd,EAAE;QACD,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;QAC5C,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,KAAK,CAAC,EAAE,OAAO,CAAC;KACjB;IA6GM,IAAI,CAAC,GAAG,GAAE,MAAkB,GAAG,IAAI;CAiB3C;AAED,eAAe,SAAS,CAAC","sources":["src/src/index.ts","src/index.ts"],"sourcesContent":[null,"declare global {\n interface Window {\n webkitAudioContext?: typeof AudioContext;\n }\n}\n\nclass ClickTone {\n private readonly file: string;\n private readonly volume: number;\n private readonly callback: ((error?: Error) => void) | null;\n private readonly throttle: number;\n private readonly debug: boolean;\n private lastClickTime: number;\n private readonly audioCache: Record<string, AudioBuffer>;\n private audioContext: AudioContext | null;\n\n constructor({\n file,\n volume = 1.0,\n callback = null,\n throttle = 0,\n debug = false,\n }: {\n file: string;\n volume?: number;\n callback?: ((error?: Error) => void) | null;\n throttle?: number;\n debug?: boolean;\n }) {\n this.file = file;\n this.volume = volume;\n this.callback = callback;\n this.throttle = throttle;\n this.debug = debug;\n this.lastClickTime = 0;\n this.audioCache = {};\n this.audioContext = null;\n }\n\n private initAudioContext(): void {\n if (!this.audioContext) {\n this.audioContext = new (window.AudioContext || window.webkitAudioContext)();\n this.iOSFixAudioContext();\n }\n }\n\n private iOSFixAudioContext(): void {\n if (this.audioContext && this.audioContext.state === 'suspended' && 'ontouchstart' in window) {\n const unlock = (): void => {\n if (this.audioContext!.state === 'suspended') {\n void this.audioContext!.resume()\n .then(() => {\n document.body.removeEventListener('touchstart', unlock);\n document.body.removeEventListener('touchend', unlock);\n })\n .catch((error) => {\n if (this.debug) {\n console.error('AudioContext resume error:', error);\n }\n });\n }\n };\n\n document.body.addEventListener('touchstart', unlock, false);\n document.body.addEventListener('touchend', unlock, false);\n }\n }\n\n private async fetchAndDecodeAudio(url: string): Promise<AudioBuffer> {\n try {\n if (this.audioCache[url]) {\n return this.audioCache[url];\n }\n\n const response = await fetch(url);\n const buffer = await response.arrayBuffer();\n const audioData = await this.audioContext!.decodeAudioData(buffer);\n\n this.audioCache[url] = audioData;\n\n return audioData;\n } catch (error) {\n if (this.debug) {\n console.error('Audio loading and decoding error: ', error);\n }\n\n throw new Error(\n `Something went wrong when loading and decoding the audio: ${(error as Error).message}`,\n );\n }\n }\n\n private async playAudio(url: string): Promise<void> {\n this.initAudioContext();\n\n try {\n const audioData = await this.fetchAndDecodeAudio(url);\n const source = this.audioContext!.createBufferSource();\n const gainNode = this.audioContext!.createGain();\n\n source.buffer = audioData;\n gainNode.gain.value = this.volume;\n source.connect(gainNode);\n gainNode.connect(this.audioContext!.destination);\n\n source.onended = (): void => {\n if (this.callback) {\n this.callback();\n }\n };\n\n source.start(0);\n } catch (error) {\n if (this.debug) {\n console.error('Audio playback error: ', error);\n }\n\n throw new Error(`Something went wrong while playing audio: ${(error as Error).message}`);\n }\n }\n\n private throttleFn(func: () => Promise<void>): () => void {\n return () => {\n const now = Date.now();\n\n if (now - this.lastClickTime >= this.throttle) {\n void func().catch((error) => {\n if (this.debug) {\n console.error('Error in throttled function:', error);\n }\n });\n\n this.lastClickTime = now;\n }\n };\n }\n\n public play(url: string = this.file): void {\n const throttledPlay = this.throttleFn(() => this.playAudio(url));\n\n try {\n throttledPlay();\n } catch (error) {\n if (this.debug) {\n console.error('Audio playback error: ', error);\n }\n\n if (this.callback) {\n this.callback(error as Error);\n } else {\n throw error;\n }\n }\n }\n}\n\nexport default ClickTone;\n"],"names":[],"version":3,"file":"clicktone.d.ts.map"}
package/dist/index.js DELETED
@@ -1,101 +0,0 @@
1
-
2
- function $parcel$defineInteropFlag(a) {
3
- Object.defineProperty(a, '__esModule', {value: true, configurable: true});
4
- }
5
-
6
- function $parcel$export(e, n, v, s) {
7
- Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
8
- }
9
-
10
- $parcel$defineInteropFlag(module.exports);
11
-
12
- $parcel$export(module.exports, "default", function () { return $a196c1ed25598f0e$export$2e2bcd8739ae039; });
13
- class $a196c1ed25598f0e$var$ClickTone {
14
- constructor({ file: file, volume: volume = 1.0, callback: callback = null, throttle: throttle = 0, debug: debug = false }){
15
- this.file = file;
16
- this.volume = volume;
17
- this.callback = callback;
18
- this.throttle = throttle;
19
- this.debug = debug;
20
- this.lastClickTime = 0;
21
- this.audioCache = {};
22
- this.audioContext = null;
23
- }
24
- initAudioContext() {
25
- if (!this.audioContext) {
26
- this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
27
- this.iOSFixAudioContext();
28
- }
29
- }
30
- iOSFixAudioContext() {
31
- if (this.audioContext && this.audioContext.state === 'suspended' && 'ontouchstart' in window) {
32
- const unlock = ()=>{
33
- if (this.audioContext.state === 'suspended') this.audioContext.resume().then(()=>{
34
- document.body.removeEventListener('touchstart', unlock);
35
- document.body.removeEventListener('touchend', unlock);
36
- }).catch((error)=>{
37
- if (this.debug) console.error('AudioContext resume error:', error);
38
- });
39
- };
40
- document.body.addEventListener('touchstart', unlock, false);
41
- document.body.addEventListener('touchend', unlock, false);
42
- }
43
- }
44
- async fetchAndDecodeAudio(url) {
45
- try {
46
- if (this.audioCache[url]) return this.audioCache[url];
47
- const response = await fetch(url);
48
- const buffer = await response.arrayBuffer();
49
- const audioData = await this.audioContext.decodeAudioData(buffer);
50
- this.audioCache[url] = audioData;
51
- return audioData;
52
- } catch (error) {
53
- if (this.debug) console.error('Audio loading and decoding error: ', error);
54
- throw new Error(`Something went wrong when loading and decoding the audio: ${error.message}`);
55
- }
56
- }
57
- async playAudio(url) {
58
- this.initAudioContext();
59
- try {
60
- const audioData = await this.fetchAndDecodeAudio(url);
61
- const source = this.audioContext.createBufferSource();
62
- const gainNode = this.audioContext.createGain();
63
- source.buffer = audioData;
64
- gainNode.gain.value = this.volume;
65
- source.connect(gainNode);
66
- gainNode.connect(this.audioContext.destination);
67
- source.onended = ()=>{
68
- if (this.callback) this.callback();
69
- };
70
- source.start(0);
71
- } catch (error) {
72
- if (this.debug) console.error('Audio playback error: ', error);
73
- throw new Error(`Something went wrong while playing audio: ${error.message}`);
74
- }
75
- }
76
- throttleFn(func) {
77
- return ()=>{
78
- const now = Date.now();
79
- if (now - this.lastClickTime >= this.throttle) {
80
- func().catch((error)=>{
81
- if (this.debug) console.error('Error in throttled function:', error);
82
- });
83
- this.lastClickTime = now;
84
- }
85
- };
86
- }
87
- play(url = this.file) {
88
- const throttledPlay = this.throttleFn(()=>this.playAudio(url));
89
- try {
90
- throttledPlay();
91
- } catch (error) {
92
- if (this.debug) console.error('Audio playback error: ', error);
93
- if (this.callback) this.callback(error);
94
- else throw error;
95
- }
96
- }
97
- }
98
- var $a196c1ed25598f0e$export$2e2bcd8739ae039 = $a196c1ed25598f0e$var$ClickTone;
99
-
100
-
101
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"mappings":";;;;;;;;;;;;AAMA,MAAM;IAUJ,YAAY,QACV,IAAI,UACJ,SAAS,eACT,WAAW,gBACX,WAAW,UACX,QAAQ,OAOT,CAAE;QACD,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,MAAM,GAAG;QACd,IAAI,CAAC,QAAQ,GAAG;QAChB,IAAI,CAAC,QAAQ,GAAG;QAChB,IAAI,CAAC,KAAK,GAAG;QACb,IAAI,CAAC,aAAa,GAAG;QACrB,IAAI,CAAC,UAAU,GAAG,CAAC;QACn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AEd,MAAM;QAEV;IACF;AACF;IAEA,2CAAe","sources":["src/index.ts"],"sourcesContent":["declare global {\n interface Window {\n webkitAudioContext?: typeof AudioContext;\n }\n}\n\nclass ClickTone {\n private readonly file: string;\n private readonly volume: number;\n private readonly callback: ((error?: Error) => void) | null;\n private readonly throttle: number;\n private readonly debug: boolean;\n private lastClickTime: number;\n private readonly audioCache: Record<string, AudioBuffer>;\n private audioContext: AudioContext | null;\n\n constructor({\n file,\n volume = 1.0,\n callback = null,\n throttle = 0,\n debug = false,\n }: {\n file: string;\n volume?: number;\n callback?: ((error?: Error) => void) | null;\n throttle?: number;\n debug?: boolean;\n }) {\n this.file = file;\n this.volume = volume;\n this.callback = callback;\n this.throttle = throttle;\n this.debug = debug;\n this.lastClickTime = 0;\n this.audioCache = {};\n this.audioContext = null;\n }\n\n private initAudioContext(): void {\n if (!this.audioContext) {\n this.audioContext = new (window.AudioContext || window.webkitAudioContext)();\n this.iOSFixAudioContext();\n }\n }\n\n private iOSFixAudioContext(): void {\n if (this.audioContext && this.audioContext.state === 'suspended' && 'ontouchstart' in window) {\n const unlock = (): void => {\n if (this.audioContext!.state === 'suspended') {\n void this.audioContext!.resume()\n .then(() => {\n document.body.removeEventListener('touchstart', unlock);\n document.body.removeEventListener('touchend', unlock);\n })\n .catch((error) => {\n if (this.debug) {\n console.error('AudioContext resume error:', error);\n }\n });\n }\n };\n\n document.body.addEventListener('touchstart', unlock, false);\n document.body.addEventListener('touchend', unlock, false);\n }\n }\n\n private async fetchAndDecodeAudio(url: string): Promise<AudioBuffer> {\n try {\n if (this.audioCache[url]) {\n return this.audioCache[url];\n }\n\n const response = await fetch(url);\n const buffer = await response.arrayBuffer();\n const audioData = await this.audioContext!.decodeAudioData(buffer);\n\n this.audioCache[url] = audioData;\n\n return audioData;\n } catch (error) {\n if (this.debug) {\n console.error('Audio loading and decoding error: ', error);\n }\n\n throw new Error(\n `Something went wrong when loading and decoding the audio: ${(error as Error).message}`,\n );\n }\n }\n\n private async playAudio(url: string): Promise<void> {\n this.initAudioContext();\n\n try {\n const audioData = await this.fetchAndDecodeAudio(url);\n const source = this.audioContext!.createBufferSource();\n const gainNode = this.audioContext!.createGain();\n\n source.buffer = audioData;\n gainNode.gain.value = this.volume;\n source.connect(gainNode);\n gainNode.connect(this.audioContext!.destination);\n\n source.onended = (): void => {\n if (this.callback) {\n this.callback();\n }\n };\n\n source.start(0);\n } catch (error) {\n if (this.debug) {\n console.error('Audio playback error: ', error);\n }\n\n throw new Error(`Something went wrong while playing audio: ${(error as Error).message}`);\n }\n }\n\n private throttleFn(func: () => Promise<void>): () => void {\n return () => {\n const now = Date.now();\n\n if (now - this.lastClickTime >= this.throttle) {\n void func().catch((error) => {\n if (this.debug) {\n console.error('Error in throttled function:', error);\n }\n });\n\n this.lastClickTime = now;\n }\n };\n }\n\n public play(url: string = this.file): void {\n const throttledPlay = this.throttleFn(() => this.playAudio(url));\n\n try {\n throttledPlay();\n } catch (error) {\n if (this.debug) {\n console.error('Audio playback error: ', error);\n }\n\n if (this.callback) {\n this.callback(error as Error);\n } else {\n throw error;\n }\n }\n }\n}\n\nexport default ClickTone;\n"],"names":[],"version":3,"file":"index.js.map"}
@@ -1,90 +0,0 @@
1
- class $643fcf18b2d2e76f$var$ClickTone {
2
- constructor({ file: file, volume: volume = 1.0, callback: callback = null, throttle: throttle = 0, debug: debug = false }){
3
- this.file = file;
4
- this.volume = volume;
5
- this.callback = callback;
6
- this.throttle = throttle;
7
- this.debug = debug;
8
- this.lastClickTime = 0;
9
- this.audioCache = {};
10
- this.audioContext = null;
11
- }
12
- initAudioContext() {
13
- if (!this.audioContext) {
14
- this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
15
- this.iOSFixAudioContext();
16
- }
17
- }
18
- iOSFixAudioContext() {
19
- if (this.audioContext && this.audioContext.state === 'suspended' && 'ontouchstart' in window) {
20
- const unlock = ()=>{
21
- if (this.audioContext.state === 'suspended') this.audioContext.resume().then(()=>{
22
- document.body.removeEventListener('touchstart', unlock);
23
- document.body.removeEventListener('touchend', unlock);
24
- }).catch((error)=>{
25
- if (this.debug) console.error('AudioContext resume error:', error);
26
- });
27
- };
28
- document.body.addEventListener('touchstart', unlock, false);
29
- document.body.addEventListener('touchend', unlock, false);
30
- }
31
- }
32
- async fetchAndDecodeAudio(url) {
33
- try {
34
- if (this.audioCache[url]) return this.audioCache[url];
35
- const response = await fetch(url);
36
- const buffer = await response.arrayBuffer();
37
- const audioData = await this.audioContext.decodeAudioData(buffer);
38
- this.audioCache[url] = audioData;
39
- return audioData;
40
- } catch (error) {
41
- if (this.debug) console.error('Audio loading and decoding error: ', error);
42
- throw new Error(`Something went wrong when loading and decoding the audio: ${error.message}`);
43
- }
44
- }
45
- async playAudio(url) {
46
- this.initAudioContext();
47
- try {
48
- const audioData = await this.fetchAndDecodeAudio(url);
49
- const source = this.audioContext.createBufferSource();
50
- const gainNode = this.audioContext.createGain();
51
- source.buffer = audioData;
52
- gainNode.gain.value = this.volume;
53
- source.connect(gainNode);
54
- gainNode.connect(this.audioContext.destination);
55
- source.onended = ()=>{
56
- if (this.callback) this.callback();
57
- };
58
- source.start(0);
59
- } catch (error) {
60
- if (this.debug) console.error('Audio playback error: ', error);
61
- throw new Error(`Something went wrong while playing audio: ${error.message}`);
62
- }
63
- }
64
- throttleFn(func) {
65
- return ()=>{
66
- const now = Date.now();
67
- if (now - this.lastClickTime >= this.throttle) {
68
- func().catch((error)=>{
69
- if (this.debug) console.error('Error in throttled function:', error);
70
- });
71
- this.lastClickTime = now;
72
- }
73
- };
74
- }
75
- play(url = this.file) {
76
- const throttledPlay = this.throttleFn(()=>this.playAudio(url));
77
- try {
78
- throttledPlay();
79
- } catch (error) {
80
- if (this.debug) console.error('Audio playback error: ', error);
81
- if (this.callback) this.callback(error);
82
- else throw error;
83
- }
84
- }
85
- }
86
- var $643fcf18b2d2e76f$export$2e2bcd8739ae039 = $643fcf18b2d2e76f$var$ClickTone;
87
-
88
-
89
- export {$643fcf18b2d2e76f$export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AI,CAAC,KAAK,EACZ,QAAQ,KAAK,CAAC,gCAAgC;gBAElD;gBAEA,IAAI,CAAC,aAAa,GAAG;YACvB;QACF;IACF;IAEO,KAAK,MAAc,IAAI,CAAC,IAAI,EAAQ;QACzC,MAAM,gBAAgB,IAAI,CAAC,UAAU,CAAC,IAAM,IAAI,CAAC,SAAS,CAAC;QAE3D,IAAI;YACF;QACF,EAAE,OAAO,OAAO;YACd,IAAI,IAAI,CAAC,KAAK,EACZ,QAAQ,KAAK,CAAC,0BAA0B;YAG1C,IAAI,IAAI,CAAC,QAAQ,EACf,IAAI,CAAC,QAAQ,CAAC;iBAEd,MAAM;QAEV;IACF;AACF;IAEA,2CAAe","sources":["src/index.ts"],"sourcesContent":["declare global {\n interface Window {\n webkitAudioContext?: typeof AudioContext;\n }\n}\n\nclass ClickTone {\n private readonly file: string;\n private readonly volume: number;\n private readonly callback: ((error?: Error) => void) | null;\n private readonly throttle: number;\n private readonly debug: boolean;\n private lastClickTime: number;\n private readonly audioCache: Record<string, AudioBuffer>;\n private audioContext: AudioContext | null;\n\n constructor({\n file,\n volume = 1.0,\n callback = null,\n throttle = 0,\n debug = false,\n }: {\n file: string;\n volume?: number;\n callback?: ((error?: Error) => void) | null;\n throttle?: number;\n debug?: boolean;\n }) {\n this.file = file;\n this.volume = volume;\n this.callback = callback;\n this.throttle = throttle;\n this.debug = debug;\n this.lastClickTime = 0;\n this.audioCache = {};\n this.audioContext = null;\n }\n\n private initAudioContext(): void {\n if (!this.audioContext) {\n this.audioContext = new (window.AudioContext || window.webkitAudioContext)();\n this.iOSFixAudioContext();\n }\n }\n\n private iOSFixAudioContext(): void {\n if (this.audioContext && this.audioContext.state === 'suspended' && 'ontouchstart' in window) {\n const unlock = (): void => {\n if (this.audioContext!.state === 'suspended') {\n void this.audioContext!.resume()\n .then(() => {\n document.body.removeEventListener('touchstart', unlock);\n document.body.removeEventListener('touchend', unlock);\n })\n .catch((error) => {\n if (this.debug) {\n console.error('AudioContext resume error:', error);\n }\n });\n }\n };\n\n document.body.addEventListener('touchstart', unlock, false);\n document.body.addEventListener('touchend', unlock, false);\n }\n }\n\n private async fetchAndDecodeAudio(url: string): Promise<AudioBuffer> {\n try {\n if (this.audioCache[url]) {\n return this.audioCache[url];\n }\n\n const response = await fetch(url);\n const buffer = await response.arrayBuffer();\n const audioData = await this.audioContext!.decodeAudioData(buffer);\n\n this.audioCache[url] = audioData;\n\n return audioData;\n } catch (error) {\n if (this.debug) {\n console.error('Audio loading and decoding error: ', error);\n }\n\n throw new Error(\n `Something went wrong when loading and decoding the audio: ${(error as Error).message}`,\n );\n }\n }\n\n private async playAudio(url: string): Promise<void> {\n this.initAudioContext();\n\n try {\n const audioData = await this.fetchAndDecodeAudio(url);\n const source = this.audioContext!.createBufferSource();\n const gainNode = this.audioContext!.createGain();\n\n source.buffer = audioData;\n gainNode.gain.value = this.volume;\n source.connect(gainNode);\n gainNode.connect(this.audioContext!.destination);\n\n source.onended = (): void => {\n if (this.callback) {\n this.callback();\n }\n };\n\n source.start(0);\n } catch (error) {\n if (this.debug) {\n console.error('Audio playback error: ', error);\n }\n\n throw new Error(`Something went wrong while playing audio: ${(error as Error).message}`);\n }\n }\n\n private throttleFn(func: () => Promise<void>): () => void {\n return () => {\n const now = Date.now();\n\n if (now - this.lastClickTime >= this.throttle) {\n void func().catch((error) => {\n if (this.debug) {\n console.error('Error in throttled function:', error);\n }\n });\n\n this.lastClickTime = now;\n }\n };\n }\n\n public play(url: string = this.file): void {\n const throttledPlay = this.throttleFn(() => this.playAudio(url));\n\n try {\n throttledPlay();\n } catch (error) {\n if (this.debug) {\n console.error('Audio playback error: ', error);\n }\n\n if (this.callback) {\n this.callback(error as Error);\n } else {\n throw error;\n }\n }\n }\n}\n\nexport default ClickTone;\n"],"names":[],"version":3,"file":"index.module.js.map"}
package/eslint.config.mjs DELETED
@@ -1,72 +0,0 @@
1
- import globals from 'globals';
2
- import eslintPlugin from '@eslint/js';
3
- import typescriptPlugin from '@typescript-eslint/eslint-plugin';
4
- import typescriptParser from '@typescript-eslint/parser';
5
- import prettierConfig from 'eslint-config-prettier';
6
- import importPlugin from 'eslint-plugin-import';
7
-
8
- /** @type {import("eslint").Linter.FlatConfig[]} */
9
- export default [
10
- {
11
- ignores: ['node_modules', 'dist', '.parcel', '.parcel-cache'],
12
- },
13
- {
14
- files: ['**/*.ts'],
15
- languageOptions: {
16
- ecmaVersion: 'latest',
17
- sourceType: 'module',
18
- parser: typescriptParser,
19
- parserOptions: {
20
- project: './tsconfig.json',
21
- },
22
- globals: {
23
- ...globals.browser,
24
- ...globals.es2022,
25
- globalThis: 'readonly',
26
- },
27
- },
28
- plugins: {
29
- '@typescript-eslint': typescriptPlugin,
30
- eslint: eslintPlugin,
31
- import: importPlugin,
32
- },
33
- settings: {
34
- 'import/resolver': {
35
- typescript: {
36
- project: './tsconfig.json',
37
- },
38
- },
39
- },
40
- rules: {
41
- ...eslintPlugin.configs.recommended.rules,
42
- ...typescriptPlugin.configs.recommended.rules,
43
- ...typescriptPlugin.configs['recommended-requiring-type-checking'].rules,
44
- '@typescript-eslint/no-unused-vars': 'error',
45
- '@typescript-eslint/explicit-function-return-type': 'warn',
46
- '@typescript-eslint/no-explicit-any': 'warn',
47
- 'import/order': [
48
- 'error',
49
- {
50
- groups: [['builtin', 'external', 'internal']],
51
- 'newlines-between': 'always',
52
- },
53
- ],
54
- '@typescript-eslint/triple-slash-reference': 'off',
55
- '@typescript-eslint/no-empty-interface': 'off',
56
- 'import/no-unresolved': 'error',
57
- 'import/no-duplicates': 'error',
58
- 'max-len': [
59
- 'error',
60
- {
61
- code: 100,
62
- ignoreUrls: true,
63
- ignoreStrings: true,
64
- ignoreTemplateLiterals: true,
65
- ignoreComments: true,
66
- },
67
- ],
68
- 'linebreak-style': ['error', 'unix'],
69
- },
70
- },
71
- prettierConfig,
72
- ];
package/src/index.ts DELETED
@@ -1,157 +0,0 @@
1
- declare global {
2
- interface Window {
3
- webkitAudioContext?: typeof AudioContext;
4
- }
5
- }
6
-
7
- class ClickTone {
8
- private readonly file: string;
9
- private readonly volume: number;
10
- private readonly callback: ((error?: Error) => void) | null;
11
- private readonly throttle: number;
12
- private readonly debug: boolean;
13
- private lastClickTime: number;
14
- private readonly audioCache: Record<string, AudioBuffer>;
15
- private audioContext: AudioContext | null;
16
-
17
- constructor({
18
- file,
19
- volume = 1.0,
20
- callback = null,
21
- throttle = 0,
22
- debug = false,
23
- }: {
24
- file: string;
25
- volume?: number;
26
- callback?: ((error?: Error) => void) | null;
27
- throttle?: number;
28
- debug?: boolean;
29
- }) {
30
- this.file = file;
31
- this.volume = volume;
32
- this.callback = callback;
33
- this.throttle = throttle;
34
- this.debug = debug;
35
- this.lastClickTime = 0;
36
- this.audioCache = {};
37
- this.audioContext = null;
38
- }
39
-
40
- private initAudioContext(): void {
41
- if (!this.audioContext) {
42
- this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
43
- this.iOSFixAudioContext();
44
- }
45
- }
46
-
47
- private iOSFixAudioContext(): void {
48
- if (this.audioContext && this.audioContext.state === 'suspended' && 'ontouchstart' in window) {
49
- const unlock = (): void => {
50
- if (this.audioContext!.state === 'suspended') {
51
- void this.audioContext!.resume()
52
- .then(() => {
53
- document.body.removeEventListener('touchstart', unlock);
54
- document.body.removeEventListener('touchend', unlock);
55
- })
56
- .catch((error) => {
57
- if (this.debug) {
58
- console.error('AudioContext resume error:', error);
59
- }
60
- });
61
- }
62
- };
63
-
64
- document.body.addEventListener('touchstart', unlock, false);
65
- document.body.addEventListener('touchend', unlock, false);
66
- }
67
- }
68
-
69
- private async fetchAndDecodeAudio(url: string): Promise<AudioBuffer> {
70
- try {
71
- if (this.audioCache[url]) {
72
- return this.audioCache[url];
73
- }
74
-
75
- const response = await fetch(url);
76
- const buffer = await response.arrayBuffer();
77
- const audioData = await this.audioContext!.decodeAudioData(buffer);
78
-
79
- this.audioCache[url] = audioData;
80
-
81
- return audioData;
82
- } catch (error) {
83
- if (this.debug) {
84
- console.error('Audio loading and decoding error: ', error);
85
- }
86
-
87
- throw new Error(
88
- `Something went wrong when loading and decoding the audio: ${(error as Error).message}`,
89
- );
90
- }
91
- }
92
-
93
- private async playAudio(url: string): Promise<void> {
94
- this.initAudioContext();
95
-
96
- try {
97
- const audioData = await this.fetchAndDecodeAudio(url);
98
- const source = this.audioContext!.createBufferSource();
99
- const gainNode = this.audioContext!.createGain();
100
-
101
- source.buffer = audioData;
102
- gainNode.gain.value = this.volume;
103
- source.connect(gainNode);
104
- gainNode.connect(this.audioContext!.destination);
105
-
106
- source.onended = (): void => {
107
- if (this.callback) {
108
- this.callback();
109
- }
110
- };
111
-
112
- source.start(0);
113
- } catch (error) {
114
- if (this.debug) {
115
- console.error('Audio playback error: ', error);
116
- }
117
-
118
- throw new Error(`Something went wrong while playing audio: ${(error as Error).message}`);
119
- }
120
- }
121
-
122
- private throttleFn(func: () => Promise<void>): () => void {
123
- return () => {
124
- const now = Date.now();
125
-
126
- if (now - this.lastClickTime >= this.throttle) {
127
- void func().catch((error) => {
128
- if (this.debug) {
129
- console.error('Error in throttled function:', error);
130
- }
131
- });
132
-
133
- this.lastClickTime = now;
134
- }
135
- };
136
- }
137
-
138
- public play(url: string = this.file): void {
139
- const throttledPlay = this.throttleFn(() => this.playAudio(url));
140
-
141
- try {
142
- throttledPlay();
143
- } catch (error) {
144
- if (this.debug) {
145
- console.error('Audio playback error: ', error);
146
- }
147
-
148
- if (this.callback) {
149
- this.callback(error as Error);
150
- } else {
151
- throw error;
152
- }
153
- }
154
- }
155
- }
156
-
157
- export default ClickTone;
package/tsconfig.json DELETED
@@ -1,14 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "isolatedModules": true,
4
- "target": "ESNext",
5
- "module": "ESNext",
6
- "strict": true,
7
- "strictNullChecks": true,
8
- "esModuleInterop": true,
9
- "skipLibCheck": true,
10
- "forceConsistentCasingInFileNames": true,
11
- "moduleResolution": "node",
12
- "noImplicitAny": true
13
- }
14
- }