@ain1084/audio-worklet-stream 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +222 -0
  2. package/README.md +243 -0
  3. package/dist/constants.d.ts +12 -0
  4. package/dist/constants.js +15 -0
  5. package/dist/constants.js.map +1 -0
  6. package/dist/events.d.ts +37 -0
  7. package/dist/events.js +35 -0
  8. package/dist/events.js.map +1 -0
  9. package/dist/frame-buffer/buffer-factory.d.ts +77 -0
  10. package/dist/frame-buffer/buffer-factory.js +52 -0
  11. package/dist/frame-buffer/buffer-factory.js.map +1 -0
  12. package/dist/frame-buffer/buffer-filler.d.ts +13 -0
  13. package/dist/frame-buffer/buffer-filler.js +2 -0
  14. package/dist/frame-buffer/buffer-filler.js.map +1 -0
  15. package/dist/frame-buffer/buffer-reader.d.ts +37 -0
  16. package/dist/frame-buffer/buffer-reader.js +51 -0
  17. package/dist/frame-buffer/buffer-reader.js.map +1 -0
  18. package/dist/frame-buffer/buffer-utils.d.ts +34 -0
  19. package/dist/frame-buffer/buffer-utils.js +34 -0
  20. package/dist/frame-buffer/buffer-utils.js.map +1 -0
  21. package/dist/frame-buffer/buffer-writer.d.ts +37 -0
  22. package/dist/frame-buffer/buffer-writer.js +51 -0
  23. package/dist/frame-buffer/buffer-writer.js.map +1 -0
  24. package/dist/frame-buffer/buffer.d.ts +40 -0
  25. package/dist/frame-buffer/buffer.js +65 -0
  26. package/dist/frame-buffer/buffer.js.map +1 -0
  27. package/dist/index.d.ts +6 -0
  28. package/dist/index.js +4 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/output-message.d.ts +42 -0
  31. package/dist/output-message.js +2 -0
  32. package/dist/output-message.js.map +1 -0
  33. package/dist/output-stream-node.d.ts +93 -0
  34. package/dist/output-stream-node.js +166 -0
  35. package/dist/output-stream-node.js.map +1 -0
  36. package/dist/output-stream-processor.d.ts +13 -0
  37. package/dist/output-stream-processor.js +99 -0
  38. package/dist/output-stream-processor.js.map +1 -0
  39. package/dist/stream-node-factory.d.ts +87 -0
  40. package/dist/stream-node-factory.js +113 -0
  41. package/dist/stream-node-factory.js.map +1 -0
  42. package/dist/write-strategy/manual.d.ts +36 -0
  43. package/dist/write-strategy/manual.js +43 -0
  44. package/dist/write-strategy/manual.js.map +1 -0
  45. package/dist/write-strategy/strategy.d.ts +23 -0
  46. package/dist/write-strategy/strategy.js +2 -0
  47. package/dist/write-strategy/strategy.js.map +1 -0
  48. package/dist/write-strategy/timed.d.ts +36 -0
  49. package/dist/write-strategy/timed.js +92 -0
  50. package/dist/write-strategy/timed.js.map +1 -0
  51. package/dist/write-strategy/worker/message.d.ts +54 -0
  52. package/dist/write-strategy/worker/message.js +2 -0
  53. package/dist/write-strategy/worker/message.js.map +1 -0
  54. package/dist/write-strategy/worker/strategy.d.ts +34 -0
  55. package/dist/write-strategy/worker/strategy.js +125 -0
  56. package/dist/write-strategy/worker/strategy.js.map +1 -0
  57. package/dist/write-strategy/worker/worker.d.ts +35 -0
  58. package/dist/write-strategy/worker/worker.js +135 -0
  59. package/dist/write-strategy/worker/worker.js.map +1 -0
  60. package/package.json +54 -0
  61. package/src/constants.ts +18 -0
  62. package/src/events.ts +43 -0
  63. package/src/frame-buffer/buffer-factory.ts +115 -0
  64. package/src/frame-buffer/buffer-filler.ts +14 -0
  65. package/src/frame-buffer/buffer-reader.ts +56 -0
  66. package/src/frame-buffer/buffer-utils.ts +48 -0
  67. package/src/frame-buffer/buffer-writer.ts +56 -0
  68. package/src/frame-buffer/buffer.ts +68 -0
  69. package/src/index.ts +9 -0
  70. package/src/output-message.ts +37 -0
  71. package/src/output-stream-node.ts +197 -0
  72. package/src/output-stream-processor.ts +124 -0
  73. package/src/stream-node-factory.ts +161 -0
  74. package/src/write-strategy/manual.ts +50 -0
  75. package/src/write-strategy/strategy.ts +26 -0
  76. package/src/write-strategy/timed.ts +103 -0
  77. package/src/write-strategy/worker/message.ts +48 -0
  78. package/src/write-strategy/worker/strategy.ts +154 -0
  79. package/src/write-strategy/worker/worker.ts +149 -0
package/LICENSE ADDED
@@ -0,0 +1,222 @@
1
+ MIT License
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
20
+
21
+
22
+ Apache License
23
+ Version 2.0, January 2004
24
+ http://www.apache.org/licenses/
25
+
26
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
27
+
28
+ 1. Definitions.
29
+
30
+ "License" shall mean the terms and conditions for use, reproduction,
31
+ and distribution as defined by Sections 1 through 9 of this document.
32
+
33
+ "Licensor" shall mean the copyright owner or entity authorized by
34
+ the copyright owner that is granting the License.
35
+
36
+ "Legal Entity" shall mean the union of the acting entity and all
37
+ other entities that control, are controlled by, or are under common
38
+ control with that entity. For the purposes of this definition,
39
+ "control" means (i) the power, direct or indirect, to cause the
40
+ direction or management of such entity, whether by contract or
41
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
42
+ outstanding shares, or (iii) beneficial ownership of such entity.
43
+
44
+ "You" (or "Your") shall mean an individual or Legal Entity
45
+ exercising permissions granted by this License.
46
+
47
+ "Source" form shall mean the preferred form for making modifications,
48
+ including but not limited to software source code, documentation
49
+ source, and configuration files.
50
+
51
+ "Object" form shall mean any form resulting from mechanical
52
+ transformation or translation of a Source form, including but
53
+ not limited to compiled object code, generated documentation,
54
+ and conversions to other media types.
55
+
56
+ "Work" shall mean the work of authorship, whether in Source or
57
+ Object form, made available under the License, as indicated by a
58
+ copyright notice that is included in or attached to the work
59
+ (an example is provided in the Appendix below).
60
+
61
+ "Derivative Works" shall mean any work, whether in Source or Object
62
+ form, that is based on (or derived from) the Work and for which the
63
+ editorial revisions, annotations, elaborations, or other modifications
64
+ represent, as a whole, an original work of authorship. For the purposes
65
+ of this License, Derivative Works shall not include works that remain
66
+ separable from, or merely link (or bind by name) to the interfaces of,
67
+ the Work and Derivative Works thereof.
68
+
69
+ "Contribution" shall mean any work of authorship, including
70
+ the original version of the Work and any modifications or additions
71
+ to that Work or Derivative Works thereof, that is intentionally
72
+ submitted to Licensor for inclusion in the Work by the copyright owner
73
+ or by an individual or Legal Entity authorized to submit on behalf of
74
+ the copyright owner. For the purposes of this definition, "submitted"
75
+ means any form of electronic, verbal, or written communication sent
76
+ to the Licensor or its representatives, including but not limited to
77
+ communication on electronic mailing lists, source code control systems,
78
+ and issue tracking systems that are managed by, or on behalf of, the
79
+ Licensor for the purpose of discussing and improving the Work, but
80
+ excluding communication that is conspicuously marked or otherwise
81
+ designated in writing by the copyright owner as "Not a Contribution."
82
+
83
+ "Contributor" shall mean Licensor and any individual or Legal Entity
84
+ on behalf of whom a Contribution has been received by Licensor and
85
+ subsequently incorporated within the Work.
86
+
87
+ 2. Grant of Copyright License. Subject to the terms and conditions of
88
+ this License, each Contributor hereby grants to You a perpetual,
89
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
90
+ copyright license to reproduce, prepare Derivative Works of,
91
+ publicly display, publicly perform, sublicense, and distribute the
92
+ Work and such Derivative Works in Source or Object form.
93
+
94
+ 3. Grant of Patent License. Subject to the terms and conditions of
95
+ this License, each Contributor hereby grants to You a perpetual,
96
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
97
+ (except as stated in this section) patent license to make, have made,
98
+ use, offer to sell, sell, import, and otherwise transfer the Work,
99
+ where such license applies only to those patent claims licensable
100
+ by such Contributor that are necessarily infringed by their
101
+ Contribution(s) alone or by combination of their Contribution(s)
102
+ with the Work to which such Contribution(s) was submitted. If You
103
+ institute patent litigation against any entity (including a
104
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
105
+ or a Contribution incorporated within the Work constitutes direct
106
+ or contributory patent infringement, then any patent licenses
107
+ granted to You under this License for that Work shall terminate
108
+ as of the date such litigation is filed.
109
+
110
+ 4. Redistribution. You may reproduce and distribute copies of the
111
+ Work or Derivative Works thereof in any medium, with or without
112
+ modifications, and in Source or Object form, provided that You
113
+ meet the following conditions:
114
+
115
+ (a) You must give any other recipients of the Work or
116
+ Derivative Works a copy of this License; and
117
+
118
+ (b) You must cause any modified files to carry prominent notices
119
+ stating that You changed the files; and
120
+
121
+ (c) You must retain, in the Source form of any Derivative Works
122
+ that You distribute, all copyright, patent, trademark, and
123
+ attribution notices from the Source form of the Work,
124
+ excluding those notices that do not pertain to any part of
125
+ the Derivative Works; and
126
+
127
+ (d) If the Work includes a "NOTICE" text file as part of its
128
+ distribution, then any Derivative Works that You distribute must
129
+ include a readable copy of the attribution notices contained
130
+ within such NOTICE file, excluding those notices that do not
131
+ pertain to any part of the Derivative Works, in at least one
132
+ of the following places: within a NOTICE text file distributed
133
+ as part of the Derivative Works; within the Source form or
134
+ documentation, if provided along with the Derivative Works; or,
135
+ within a display generated by the Derivative Works, if and
136
+ wherever such third-party notices normally appear. The contents
137
+ of the NOTICE file are for informational purposes only and
138
+ do not modify the License. You may add Your own attribution
139
+ notices within Derivative Works that You distribute, alongside
140
+ or as an addendum to the NOTICE text from the Work, provided
141
+ that such additional attribution notices cannot be construed
142
+ as modifying the License.
143
+
144
+ You may add Your own copyright statement to Your modifications and
145
+ may provide additional or different license terms and conditions
146
+ for use, reproduction, or distribution of Your modifications, or
147
+ for any such Derivative Works as a whole, provided Your use,
148
+ reproduction, and distribution of the Work otherwise complies with
149
+ the conditions stated in this License.
150
+
151
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
152
+ any Contribution intentionally submitted for inclusion in the Work
153
+ by You to the Licensor shall be under the terms and conditions of
154
+ this License, without any additional terms or conditions.
155
+ Notwithstanding the above, nothing herein shall supersede or modify
156
+ the terms of any separate license agreement you may have executed
157
+ with Licensor regarding such Contributions.
158
+
159
+ 6. Trademarks. This License does not grant permission to use the trade
160
+ names, trademarks, service marks, or product names of the Licensor,
161
+ except as required for describing the origin of the Work and
162
+ reproducing the content of the NOTICE file.
163
+
164
+ 7. Disclaimer of Warranty. Unless required by applicable law or
165
+ agreed to in writing, Licensor provides the Work (and each
166
+ Contributor provides its Contributions) on an "AS IS" BASIS,
167
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
168
+ implied, including, without limitation, any warranties or conditions
169
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
170
+ PARTICULAR PURPOSE. You are solely responsible for determining the
171
+ appropriateness of using or redistributing the Work and assume any
172
+ risks associated with Your exercise of permissions under this License.
173
+
174
+ 8. Limitation of Liability. In no event and under no legal theory,
175
+ whether in tort (including negligence), contract, or otherwise,
176
+ unless required by applicable law (such as deliberate and grossly
177
+ negligent acts) or agreed to in writing, shall any Contributor be
178
+ liable to You for damages, including any direct, indirect, special,
179
+ incidental, or consequential damages of any character arising as a
180
+ result of this License or out of the use or inability to use the
181
+ Work (including but not limited to damages for loss of goodwill,
182
+ work stoppage, computer failure or malfunction, or any and all
183
+ other commercial damages or losses), even if such Contributor
184
+ has been advised of the possibility of such damages.
185
+
186
+ 9. Accepting Warranty or Additional Liability. While redistributing
187
+ the Work or Derivative Works thereof, You may choose to offer,
188
+ and charge a fee for, acceptance of support, warranty, indemnity,
189
+ or other liability obligations and/or rights consistent with this
190
+ License. However, in accepting such obligations, You may act only
191
+ on Your own behalf and on Your sole responsibility, not on behalf
192
+ of any other Contributor, and only if You agree to indemnify,
193
+ defend, and hold each Contributor harmless for any liability
194
+ incurred by, or claims asserted against, such Contributor by reason
195
+ of your accepting any such warranty or additional liability.
196
+
197
+ END OF TERMS AND CONDITIONS
198
+
199
+ APPENDIX: How to apply the Apache License to your work.
200
+
201
+ To apply the Apache License to your work, attach the following
202
+ boilerplate notice, with the fields enclosed by brackets "{}"
203
+ replaced with your own identifying information. (Don't include
204
+ the brackets!) The text should be enclosed in the appropriate
205
+ comment syntax for the file format. We also recommend that a
206
+ file or class name and description of purpose be included on the
207
+ same "printed page" as the copyright notice for easier
208
+ identification within third-party archives.
209
+
210
+ Copyright {yyyy} {name of copyright owner}
211
+
212
+ Licensed under the Apache License, Version 2.0 (the "License");
213
+ you may not use this file except in compliance with the License.
214
+ You may obtain a copy of the License at
215
+
216
+ http://www.apache.org/licenses/LICENSE-2.0
217
+
218
+ Unless required by applicable law or agreed to in writing, software
219
+ distributed under the License is distributed on an "AS IS" BASIS,
220
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
221
+ See the License for the specific language governing permissions and
222
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,243 @@
1
+ # Audio Worklet Stream Library
2
+
3
+ This library provides a way to work with audio worklets and streams using modern web technologies. It allows for the manual writing of audio frames to a buffer and supports various buffer writing strategies.
4
+
5
+ ## Features
6
+
7
+ - **Manual Buffer Writing**: Provides the ability to manually write audio frames to a buffer.
8
+ - **Multiple Buffer Writing Strategies**: Includes support for various strategies like manual, timer-based, and worker-based buffer writing.
9
+ - **Worker-Based Stability**: Utilizes Workers to ensure stable and consistent audio playback.
10
+ - **Vite Integration**: Leverages Vite for easy worker loading and configuration without complex setup.
11
+ - **Audio Worklet Integration**: Seamlessly integrates with the Web Audio API's Audio Worklet for real-time audio processing.
12
+
13
+ ## Prerequisites
14
+
15
+ - **Node.js** and **npm**: Make sure you have Node.js (version 20 or higher) and npm installed. This library hasn't been tested on versions below 20.
16
+ - **Vite**: This library uses Vite as the bundler for its simplicity in loading and configuring workers. The developer uses Nuxt3, which is compatible with Vite.
17
+
18
+ ## Installation
19
+
20
+ To install the library, run:
21
+
22
+ ```bash
23
+ npm install @ain1084/audio-worklet-stream
24
+ ```
25
+
26
+ You need to add `@ain1084/audio-worklet-stream` to the optimizeDeps.exclude section in `vite.config.ts`. Furthermore, include the necessary CORS settings to enable the use of `SharedArrayBuffer`.
27
+
28
+ **vite.config.ts**
29
+ ```typescript
30
+ import { defineConfig } from 'vite'
31
+
32
+ export default defineConfig({
33
+ optimizeDeps: {
34
+ exclude: ['@ain1084/audio-worklet-stream']
35
+ },
36
+ plugins: [
37
+ {
38
+ name: 'configure-response-headers',
39
+ configureServer: (server) => {
40
+ server.middlewares.use((_req, res, next) => {
41
+ res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
42
+ res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
43
+ next()
44
+ })
45
+ },
46
+ },
47
+ ],
48
+ })
49
+ ```
50
+
51
+ If you are using Nuxt3, add it under vite in `nuxt.config.ts`.
52
+
53
+ **nuxt.config.ts**
54
+ ```typescript
55
+ export default defineNuxtConfig({
56
+ vite: {
57
+ optimizeDeps: {
58
+ exclude: ['@ain1084/audio-worklet-stream']
59
+ },
60
+ plugins: [
61
+ {
62
+ name: 'configure-response-headers',
63
+ configureServer: (server) => {
64
+ server.middlewares.use((_req, res, next) => {
65
+ res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
66
+ res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
67
+ next()
68
+ })
69
+ },
70
+ },
71
+ ],
72
+ },
73
+ })
74
+ ```
75
+
76
+ Additionally, add the Nitro configuration (needed when running `npm run build`).
77
+
78
+ **nuxt.config.ts**
79
+ ```typescript
80
+ export default defineNuxtConfig({
81
+ nitro: {
82
+ rollupConfig: {
83
+ external: '@ain1084/audio-worklet-stream',
84
+ },
85
+ routeRules: {
86
+ '/**': {
87
+ cors: true,
88
+ headers: {
89
+ 'Cross-Origin-Embedder-Policy': 'require-corp',
90
+ 'Cross-Origin-Opener-Policy': 'same-origin',
91
+ },
92
+ },
93
+ },
94
+ },
95
+ })
96
+ ```
97
+
98
+ ## Usage
99
+
100
+ ### Overview
101
+
102
+ This library continuously plays audio sample frames using `AudioWorkletNode`. The audio sample frames need to be supplied externally via a ring buffer. The library provides functionality to retrieve the number of written and read (played) frames and allows stopping playback at a specified frame.
103
+
104
+ ### Buffer Writing Methods
105
+
106
+ - **Manual**: The consumer is responsible for writing to the ring buffer. If the buffer becomes empty, silence is played. This method requires active management to ensure the buffer is always filled with audio data.
107
+ - *Example*:
108
+ ```typescript
109
+ const writer = await main.createManualNode();
110
+ // Write arbitrary audio frames
111
+ writer.write(...);
112
+ main.start();
113
+ ```
114
+
115
+ - **Timed**: Uses a UI thread timer to periodically write to the buffer. Frames to be written to the buffer are requested through `FrameBufferFiller`.
116
+ - *Example*:
117
+ ```typescript
118
+ await main.createTimedNode();
119
+ main.start();
120
+ ```
121
+
122
+ - **Worker**: Similar to Timed but uses a timer in a Worker instead of the UI thread. This approach provides more stable playback by avoiding UI thread throttling. See the [MDN Web Docs on setInterval delay restrictions](https://developer.mozilla.org/en-US/docs/Web/API/setInterval#delay_restrictions) for more details.
123
+ - *Example*:
124
+ ```typescript
125
+ await main.createWorkerNode();
126
+ main.start();
127
+ ```
128
+
129
+ Below is a reference implementation of `main` used in the examples.
130
+
131
+ Note: The imported `sine-wave-frame-buffer-filler` and `worker` can be found in the `example/src/` directory.
132
+
133
+ ```typescript
134
+ import { StreamNodeFactory, type OutputStreamNode } from '@ain1084/audio-worklet-stream';
135
+ import worker from './worker?worker';
136
+ import type { FillerParameters } from './sine-wave-frame-buffer-filler';
137
+ import { SineWaveFrameBufferFiller } from './sine-wave-frame-buffer-filler';
138
+
139
+ class Main {
140
+ private factory: StreamNodeFactory | null = null;
141
+ private streamNode: OutputStreamNode | null = null;
142
+
143
+ // Initialize the AudioContext and StreamNodeFactory
144
+ async init() {
145
+ const audioContext = new AudioContext();
146
+ this.factory = await StreamNodeFactory.create(audioContext);
147
+ }
148
+
149
+ // Create a manual buffer node
150
+ async createManualNode() {
151
+ if (!this.factory) throw new Error('Factory not initialized');
152
+ const [node, writer] = await this.factory.createManualBufferNode({
153
+ channelCount: 2,
154
+ frameBufferSize: 4096,
155
+ });
156
+ this.streamNode = node;
157
+ return writer;
158
+ }
159
+
160
+ // Create a timed buffer node
161
+ async createTimedNode() {
162
+ if (!this.factory) throw new Error('Factory not initialized');
163
+ const filler = new SineWaveFrameBufferFiller({ frequency: 440, sampleRate: 44100 });
164
+ this.streamNode = await this.factory.createTimedBufferNode(filler, {
165
+ channelCount: 2,
166
+ fillInterval: 20,
167
+ sampleRate: 44100,
168
+ });
169
+ }
170
+
171
+ // Create a worker buffer node
172
+ async createWorkerNode() {
173
+ if (!this.factory) throw new Error('Factory not initialized');
174
+ this.streamNode = await this.factory.createWorkerBufferNode<FillerParameters>(worker, {
175
+ channelCount: 2,
176
+ fillInterval: 20,
177
+ sampleRate: 44100,
178
+ fillerParams: { frequency: 440, sampleRate: 44100 },
179
+ });
180
+ }
181
+
182
+ // Start the audio stream
183
+ start() {
184
+ if (!this.streamNode) throw new Error('Stream node not created');
185
+ this.streamNode.connect(this.streamNode.context.destination);
186
+ this.streamNode.start();
187
+ }
188
+
189
+ // Stop the audio stream
190
+ stop() {
191
+ if (!this.streamNode) throw new Error('Stream node not created');
192
+ this.streamNode.stop();
193
+ }
194
+ }
195
+
196
+ export default new Main();
197
+ ```
198
+
199
+ ## Documentation
200
+
201
+ For more detailed documentation, visit the [API documentation](https://ain1084.github.io/audio-worklet-stream/).
202
+
203
+ ## Provided Example
204
+
205
+ The provided example demonstrates how to use the library to manually write audio frames to a buffer. It includes:
206
+
207
+ - **Main Application** (`example/src/main.ts`): Sets up and starts the audio stream using different buffer writing strategies.
208
+ - **Sine Wave Filler** (`example/src/sine-wave-frame-buffer-filler.ts`): Implements a frame buffer filler that generates a sine wave.
209
+ - **Sine Wave Generator** (`example/src/sine-wave-generator.ts`): Generates sine wave values for the buffer filler.
210
+ - **Worker** (`example/src/worker.ts`): Sets up a worker to handle buffer filling tasks.
211
+ - **HTML Entry Point** (`example/index.html`): Provides the HTML structure and buttons to control the audio stream.
212
+
213
+ For more details, refer to the `example/README.md`.
214
+
215
+ ## Future Plans and Known Issues
216
+
217
+ ### Future Plans
218
+ 1. **Enhanced Documentation**: Improve the documentation with more examples and detailed explanations.
219
+
220
+ ### Known Issues
221
+ 1. **Buffer Underruns**: Occasional buffer underruns under heavy CPU load.
222
+ 2. **Limited Worker Support**: Advanced features in workers might not be fully supported across all browsers.
223
+ 3. **Overhead at the Start of Playback**: The ring buffer is being generated each time.
224
+ 4. **Overhead during Worker Playback**: It seems that the Worker is being loaded every time playback starts (although it hits the cache).
225
+
226
+ We are continuously working on these areas to improve the library. Contributions and suggestions are always welcome!
227
+
228
+ ## Notes
229
+
230
+ - **Vite as a Bundler**: This library utilizes Vite to enable the loading and placement of workers without complex configurations. It may not work out-of-the-box with WebPack due to differences in how bundlers handle workers. While similar methods may exist for WebPack, this library currently only supports Vite. Initially, a bundler-independent approach was considered, but a suitable method could not be found.
231
+
232
+ - **Security Requirements**: Since this library uses `SharedArrayBuffer`, ensuring browser compatibility requires meeting specific security requirements. For more details, refer to the [MDN Web Docs on SharedArrayBuffer Security Requirements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements).
233
+
234
+
235
+ ## Contribution
236
+
237
+ Contributions are welcome! Please open an issue or submit a pull request on GitHub.
238
+
239
+ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
240
+
241
+ ## License
242
+
243
+ This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for details.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The name of the output stream processor, used as the name of the AudioWorkletProcessor.
3
+ */
4
+ export declare const PROCESSOR_NAME = "@ain1084/audio-worklet-stream/output-stream-processor";
5
+ /**
6
+ * The event type for the stop event.
7
+ */
8
+ export declare const STOP_EVENT_TYPE = "@ain1084/audio-worklet-stream/stop";
9
+ /**
10
+ * The event type for the underrun event.
11
+ */
12
+ export declare const UNDERRUN_EVENT_TYPE = "@ain1084/audio-worklet-stream/underrun";
@@ -0,0 +1,15 @@
1
+ // Constants file
2
+ const PREFIX = '@ain1084/audio-worklet-stream';
3
+ /**
4
+ * The name of the output stream processor, used as the name of the AudioWorkletProcessor.
5
+ */
6
+ export const PROCESSOR_NAME = `${PREFIX}/output-stream-processor`;
7
+ /**
8
+ * The event type for the stop event.
9
+ */
10
+ export const STOP_EVENT_TYPE = `${PREFIX}/stop`;
11
+ /**
12
+ * The event type for the underrun event.
13
+ */
14
+ export const UNDERRUN_EVENT_TYPE = `${PREFIX}/underrun`;
15
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,iBAAiB;AAEjB,MAAM,MAAM,GAAG,+BAA+B,CAAA;AAE9C;;GAEG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,MAAM,0BAA0B,CAAA;AAEjE;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,MAAM,OAAO,CAAA;AAE/C;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,MAAM,WAAW,CAAA"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Represents a custom event indicating that the audio processing has stopped.
3
+ * This event is dispatched when the audio processing stops.
4
+ */
5
+ export declare class StopEvent extends Event {
6
+ readonly frames: bigint;
7
+ static readonly type = "@ain1084/audio-worklet-stream/stop";
8
+ /**
9
+ * Creates an instance of StopEvent.
10
+ * @param frames - The position in the audio stream where the stop occurred.
11
+ */
12
+ constructor(frames: bigint);
13
+ }
14
+ /**
15
+ * Represents a custom event indicating that an underrun occurred in the audio processing.
16
+ * UnderrunEvent is triggered not at the moment the underrun occurs, but when the underrun is resolved
17
+ * or just before the node stops.
18
+ */
19
+ export declare class UnderrunEvent extends Event {
20
+ readonly frames: number;
21
+ static readonly type = "@ain1084/audio-worklet-stream/underrun";
22
+ /**
23
+ * Creates an instance of UnderrunEvent.
24
+ * @param frames - The number of frames that were not processed due to the underrun.
25
+ */
26
+ constructor(frames: number);
27
+ }
28
+ /**
29
+ * Extends the AudioWorkletNodeEventMap interface to include the custom events.
30
+ * This allows the custom events to be used in the context of AudioWorkletNode.
31
+ */
32
+ declare global {
33
+ interface AudioWorkletNodeEventMap {
34
+ [StopEvent.type]: StopEvent;
35
+ [UnderrunEvent.type]: UnderrunEvent;
36
+ }
37
+ }
package/dist/events.js ADDED
@@ -0,0 +1,35 @@
1
+ import { STOP_EVENT_TYPE, UNDERRUN_EVENT_TYPE } from './constants';
2
+ /**
3
+ * Represents a custom event indicating that the audio processing has stopped.
4
+ * This event is dispatched when the audio processing stops.
5
+ */
6
+ export class StopEvent extends Event {
7
+ frames;
8
+ static type = STOP_EVENT_TYPE;
9
+ /**
10
+ * Creates an instance of StopEvent.
11
+ * @param frames - The position in the audio stream where the stop occurred.
12
+ */
13
+ constructor(frames) {
14
+ super(StopEvent.type);
15
+ this.frames = frames;
16
+ }
17
+ }
18
+ /**
19
+ * Represents a custom event indicating that an underrun occurred in the audio processing.
20
+ * UnderrunEvent is triggered not at the moment the underrun occurs, but when the underrun is resolved
21
+ * or just before the node stops.
22
+ */
23
+ export class UnderrunEvent extends Event {
24
+ frames;
25
+ static type = UNDERRUN_EVENT_TYPE;
26
+ /**
27
+ * Creates an instance of UnderrunEvent.
28
+ * @param frames - The number of frames that were not processed due to the underrun.
29
+ */
30
+ constructor(frames) {
31
+ super(UnderrunEvent.type);
32
+ this.frames = frames;
33
+ }
34
+ }
35
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAElE;;;GAGG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAMN;IALrB,MAAM,CAAU,IAAI,GAAG,eAAe,CAAA;IAC7C;;;OAGG;IACH,YAA4B,MAAc;QACxC,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;QADK,WAAM,GAAN,MAAM,CAAQ;IAE1C,CAAC;;AAGH;;;;GAIG;AACH,MAAM,OAAO,aAAc,SAAQ,KAAK;IAMV;IALrB,MAAM,CAAU,IAAI,GAAG,mBAAmB,CAAA;IACjD;;;OAGG;IACH,YAA4B,MAAc;QACxC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;QADC,WAAM,GAAN,MAAM,CAAQ;IAE1C,CAAC"}
@@ -0,0 +1,77 @@
1
+ import { FrameBufferWriter } from './buffer-writer';
2
+ /**
3
+ * Parameters for creating a FrameBuffer.
4
+ * @property frameBufferSize - The size of the frame buffer.
5
+ * @property channelCount - The number of audio channels.
6
+ */
7
+ export type FrameBufferParams = Readonly<{
8
+ frameBufferSize: number;
9
+ channelCount: number;
10
+ }>;
11
+ /**
12
+ * Parameters for creating a FillerFrameBuffer.
13
+ * @property channelCount - The number of audio channels.
14
+ * @property fillInterval - The interval in milliseconds for filling the buffer.
15
+ * @property sampleRate - The sample rate of the audio context.
16
+ * @property frameBufferChunks - The number of chunks in the frame buffer.
17
+ */
18
+ export type FillerFrameBufferParams = Readonly<{
19
+ channelCount: number;
20
+ fillInterval?: number;
21
+ sampleRate?: number;
22
+ frameBufferChunks?: number;
23
+ }>;
24
+ /**
25
+ * Configuration for a FrameBuffer.
26
+ * This configuration is returned by the createFrameBufferConfig function.
27
+ * @property sampleBuffer - The shared buffer for audio data frames.
28
+ * @property samplesPerFrame - The number of samples per frame.
29
+ * @property usedFramesInBuffer - The usage count of the frames in the buffer.
30
+ * @property totalReadFrames - The total frames read from the buffer.
31
+ * @property totalWriteFrames - The total frames written to the buffer.
32
+ */
33
+ export type FrameBufferConfig = Readonly<{
34
+ sampleBuffer: Float32Array;
35
+ samplesPerFrame: number;
36
+ usedFramesInBuffer: Uint32Array;
37
+ totalReadFrames: BigUint64Array;
38
+ totalWriteFrames: BigUint64Array;
39
+ }>;
40
+ /**
41
+ * Configuration for a FillerFrameBuffer.
42
+ * This configuration is returned by the createFillerFrameBufferConfig function.
43
+ * @property sampleRate - The sample rate of the audio context.
44
+ * @property fillInterval - The interval in milliseconds for filling the buffer.
45
+ */
46
+ export type FillerFrameBufferConfig = FrameBufferConfig & Readonly<{
47
+ sampleRate: number;
48
+ fillInterval: number;
49
+ }>;
50
+ /**
51
+ * Creates a FrameBufferWriter instance.
52
+ * @param config - The configuration for the FrameBuffer.
53
+ * @returns A new instance of FrameBufferWriter.
54
+ */
55
+ export declare const createFrameBufferWriter: (config: FrameBufferConfig) => FrameBufferWriter;
56
+ /**
57
+ * FrameBufferFactory class
58
+ * Provides static methods to create frame buffer configurations and writers.
59
+ */
60
+ export declare class FrameBufferFactory {
61
+ static readonly DEFAULT_FILL_INTERVAL_MS = 20;
62
+ static readonly DEFAULT_FRAME_BUFFER_CHUNKS = 5;
63
+ static readonly PROCESS_UNIT = 128;
64
+ /**
65
+ * Creates a FrameBufferConfig instance.
66
+ * @param params - The parameters for the FrameBuffer.
67
+ * @returns A new instance of FrameBufferConfig.
68
+ */
69
+ static createFrameBufferConfig(params: FrameBufferParams): FrameBufferConfig;
70
+ /**
71
+ * Creates a FillerFrameBufferConfig instance.
72
+ * @param defaultSampleRate - The sample rate of the audio context.
73
+ * @param params - The parameters for the FillerFrameBuffer.
74
+ * @returns A new instance of FillerFrameBufferConfig.
75
+ */
76
+ static createFillerFrameBufferConfig(defaultSampleRate: number, params: FillerFrameBufferParams): FillerFrameBufferConfig;
77
+ }