@music-ui/osc 0.0.0-stage → 0.18.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.
@@ -0,0 +1,185 @@
1
+ import { EventEmitter } from 'events';
2
+ import { ElementOrSelector } from '@music-ui/core';
3
+
4
+ /**
5
+ * The events triggered by the player.
6
+ */
7
+ type OscPlayerEvents = "start" | "finished" | "noAvailableVoices" | "allFinished";
8
+ /**
9
+ * The osc player event listener callback.
10
+ * @property id The current osc id.
11
+ */
12
+ type OscPlayerCallback = (params: {
13
+ id: string;
14
+ }) => void;
15
+ /**
16
+ * The parameters accepted by the OscPlayer constructor.
17
+ * @property context The AudioContext used for playback
18
+ * @property analyzer The AnalyserNode used by the oscilloscope
19
+ * @property voices The max allowed playback voices
20
+ */
21
+ type OscPlayerConstructors = {
22
+ context: AudioContext;
23
+ analyzer: AnalyserNode;
24
+ voices?: number;
25
+ };
26
+ /**
27
+ * The parameters accepted by the play function.
28
+ * @property id The oscillator unique identifier
29
+ * @property frequency The oscillator frequency
30
+ * @property duration The playback duration
31
+ * @property volume The playback volume
32
+ * @property fadeInTime The playback fade in time
33
+ * @property fadeOutTime The playback fade out time
34
+ */
35
+ type OscPlayParams = {
36
+ id: string;
37
+ frequency: number;
38
+ duration: number;
39
+ volume: number;
40
+ fadeInTime?: number;
41
+ fadeOutTime?: number;
42
+ };
43
+ declare class OscPlayer {
44
+ private context;
45
+ private eventEmitter;
46
+ private analyser;
47
+ private data;
48
+ private oscillators;
49
+ /**
50
+ * Creates an `OscPlayer` instance.
51
+ *
52
+ * @param __namedParameters The accepted params
53
+ */
54
+ constructor({ context, analyzer, voices, }: OscPlayerConstructors);
55
+ /**
56
+ * Returns the analyzer data at the current time
57
+ * @returns the analyzer data
58
+ */
59
+ getData(): Uint8Array<ArrayBuffer>;
60
+ /**
61
+ * @returns the current AudioContext
62
+ */
63
+ getAudioContext(): AudioContext;
64
+ /**
65
+ * Listens to the passed OscPlayer event
66
+ * @param eventName The event name
67
+ * @param callback The event callback
68
+ * @returns The corresponding unsubscribe function
69
+ */
70
+ on(eventName: OscPlayerEvents, callback: OscPlayerCallback): () => EventEmitter;
71
+ /**
72
+ * Clears all event listeners and future playback scheduled events.
73
+ */
74
+ destroy(): void;
75
+ /**
76
+ * Schedules immediate playback.
77
+ * @param __namedParameters The accepted params
78
+ * @returns The current OscPlayer instance
79
+ */
80
+ play({ id, frequency, duration, volume, fadeInTime, fadeOutTime, }: OscPlayParams): this | undefined;
81
+ }
82
+
83
+ /**
84
+ * @property {string} content The oscillator element class
85
+ * @property {string} value The oscillator value element class
86
+ * @property {string} controls The oscillator controls element class
87
+ */
88
+ declare const cssClasses: {
89
+ readonly oscillator: "oscillator";
90
+ readonly value: "value";
91
+ readonly controls: "controls";
92
+ };
93
+ declare const DEFAULT_OSCILLATOR_PARAMS: {
94
+ readonly frequency: 440;
95
+ readonly volume: 0.5;
96
+ readonly duration: 1;
97
+ readonly label: "";
98
+ readonly playbackLabel: "Play";
99
+ };
100
+ /**
101
+ * The parameters accepted by the Oscillator constructor.
102
+ *
103
+ * @property player The OscPlayer instance
104
+ * @property element The element where the oscillator will be rendered
105
+ * @property id The oscillator unique identifier
106
+ * @property frequency The oscillator frequency
107
+ * @property volume The oscillator volume
108
+ * @property label The oscillator label
109
+ * @property playbackLabel The oscillator playback button label
110
+ */
111
+ type OscillatorParams = {
112
+ player: OscPlayer;
113
+ element: HTMLElement;
114
+ id: string;
115
+ frequency?: number;
116
+ volume?: number;
117
+ duration?: number;
118
+ label?: string;
119
+ playbackLabel?: string;
120
+ };
121
+ declare class Oscillator {
122
+ private player;
123
+ private element;
124
+ private id;
125
+ private frequency;
126
+ private volume;
127
+ private duration;
128
+ private label;
129
+ private playbackLabel;
130
+ private rendered;
131
+ private playbackButton;
132
+ /**
133
+ * Creates an `Oscillator` instance.
134
+ *
135
+ * @param __namedParameters The accepted params
136
+ */
137
+ constructor({ player, element, id, frequency, volume, duration, label, playbackLabel, }: OscillatorParams);
138
+ /**
139
+ * Sets the new frequency value, clamped to the audible frequency bounds.
140
+ * @param frequency The new frequency value
141
+ * @returns The current Oscillator instance
142
+ */
143
+ setFrequency(frequency: number): Oscillator;
144
+ /**
145
+ * @returns the oscillator frequency
146
+ */
147
+ getFrequency(): number;
148
+ /**
149
+ * Renders the UI inside the current element.
150
+ * @returns The current Oscillator instance.
151
+ */
152
+ render(): Oscillator;
153
+ private onPlay;
154
+ private baseRender;
155
+ }
156
+
157
+ /**
158
+ * The params expected by the `initOscillator` function.
159
+ * @property selection The elements to be initialized.
160
+ */
161
+ type InitOscillatorParams<T extends HTMLElement> = {
162
+ selection: ElementOrSelector<T>;
163
+ player: OscPlayer;
164
+ };
165
+ declare const DEFAULT_OPTIONS: {
166
+ readonly selection: ".oscillator";
167
+ };
168
+ /**
169
+ * Initializes oscillators on the passed selection.
170
+ * @param params The initialization params.
171
+ */
172
+ declare function initOscillator<T extends HTMLElement>(params?: Partial<InitOscillatorParams<T>>): void;
173
+
174
+ /**
175
+ * The params expected by the `initOscillatorWithOscilloscope` function.
176
+ * @property player An `OscPlayer` instance.
177
+ */
178
+ type InitOscillatorWithOscilloscopeParams<T extends HTMLElement> = InitOscillatorParams<T>;
179
+ /**
180
+ * Initializes oscillators and oscilloscope on the passed selection.
181
+ * @param params The initialization params.
182
+ */
183
+ declare function initOscillatorWithOscilloscope<T extends HTMLElement>(params: Partial<InitOscillatorWithOscilloscopeParams<T>>): void;
184
+
185
+ export { DEFAULT_OPTIONS, DEFAULT_OSCILLATOR_PARAMS, type InitOscillatorParams, OscPlayer, type OscPlayerCallback, type OscPlayerEvents, Oscillator, type OscillatorParams, cssClasses, initOscillator, initOscillatorWithOscilloscope };
package/dist/index.js ADDED
@@ -0,0 +1,466 @@
1
+ // src/OscPlayer.ts
2
+ import { EventEmitter } from "events";
3
+ var DEFAULT_MAX_VOICES = 2;
4
+ var DEFAULT_FADE_IN_TIME = 0.05;
5
+ var DEFAULT_FADE_OUT_TIME = 0.05;
6
+ var OscPlayer = class {
7
+ context;
8
+ eventEmitter;
9
+ analyser;
10
+ data;
11
+ oscillators;
12
+ /**
13
+ * Creates an `OscPlayer` instance.
14
+ *
15
+ * @param __namedParameters The accepted params
16
+ */
17
+ constructor({
18
+ context,
19
+ analyzer,
20
+ voices = DEFAULT_MAX_VOICES
21
+ }) {
22
+ this.context = context;
23
+ this.eventEmitter = new EventEmitter();
24
+ this.analyser = analyzer;
25
+ this.analyser.connect(context.destination);
26
+ this.data = new Uint8Array(this.analyser.frequencyBinCount);
27
+ this.oscillators = Array.from({ length: voices }, () => {
28
+ const osc = context.createOscillator();
29
+ const gain = context.createGain();
30
+ osc.connect(gain);
31
+ gain.connect(this.analyser);
32
+ return {
33
+ playing: false,
34
+ started: false,
35
+ osc,
36
+ gain,
37
+ timeout: -1
38
+ };
39
+ });
40
+ }
41
+ /**
42
+ * Returns the analyzer data at the current time
43
+ * @returns the analyzer data
44
+ */
45
+ getData() {
46
+ this.analyser.getByteTimeDomainData(this.data);
47
+ return this.data;
48
+ }
49
+ /**
50
+ * @returns the current AudioContext
51
+ */
52
+ getAudioContext() {
53
+ return this.context;
54
+ }
55
+ /**
56
+ * Listens to the passed OscPlayer event
57
+ * @param eventName The event name
58
+ * @param callback The event callback
59
+ * @returns The corresponding unsubscribe function
60
+ */
61
+ on(eventName, callback) {
62
+ this.eventEmitter.addListener(eventName, callback);
63
+ return () => this.eventEmitter.removeListener(eventName, callback);
64
+ }
65
+ /**
66
+ * Clears all event listeners and future playback scheduled events.
67
+ */
68
+ destroy() {
69
+ this.oscillators.forEach(({ osc, gain, timeout, started }) => {
70
+ gain.disconnect();
71
+ osc.disconnect();
72
+ if (started) {
73
+ osc.stop();
74
+ }
75
+ clearTimeout(timeout);
76
+ });
77
+ this.eventEmitter.removeAllListeners();
78
+ }
79
+ /**
80
+ * Schedules immediate playback.
81
+ * @param __namedParameters The accepted params
82
+ * @returns The current OscPlayer instance
83
+ */
84
+ play({
85
+ id,
86
+ frequency,
87
+ duration,
88
+ volume,
89
+ fadeInTime = DEFAULT_FADE_IN_TIME,
90
+ fadeOutTime = DEFAULT_FADE_OUT_TIME
91
+ }) {
92
+ if (this.oscillators.every(({ timeout }) => timeout > -1)) {
93
+ console.warn("All oscillators are already playing");
94
+ this.eventEmitter.emit("noAvailableVoices", { id });
95
+ return;
96
+ }
97
+ const { currentTime } = this.context;
98
+ const oscillator = this.oscillators.find(({ timeout }) => timeout < 0);
99
+ oscillator.osc.frequency.value = frequency;
100
+ if (!oscillator.started) {
101
+ oscillator.started = true;
102
+ oscillator.osc.start();
103
+ }
104
+ oscillator.gain.gain.setValueAtTime(0, currentTime);
105
+ oscillator.gain.gain.linearRampToValueAtTime(
106
+ volume,
107
+ currentTime + fadeInTime
108
+ );
109
+ oscillator.gain.gain.setValueAtTime(
110
+ volume,
111
+ currentTime + duration - fadeOutTime
112
+ );
113
+ oscillator.gain.gain.linearRampToValueAtTime(0, currentTime + duration);
114
+ this.eventEmitter.emit("start", { id });
115
+ oscillator.timeout = setTimeout(() => {
116
+ oscillator.timeout = -1;
117
+ this.eventEmitter.emit("finished", { id });
118
+ if (this.oscillators.some(({ timeout }) => timeout === -1)) {
119
+ return;
120
+ }
121
+ this.eventEmitter.emit("allFinished");
122
+ }, duration * 1e3);
123
+ return this;
124
+ }
125
+ };
126
+
127
+ // src/oscillator.ts
128
+ var FREQUENCY_BOUNDS = [20, 2e4];
129
+ var cssClasses = {
130
+ oscillator: "oscillator",
131
+ value: "value",
132
+ controls: "controls"
133
+ };
134
+ var DEFAULT_OSCILLATOR_PARAMS = {
135
+ frequency: 440,
136
+ volume: 0.5,
137
+ duration: 1,
138
+ label: "",
139
+ playbackLabel: "Play"
140
+ };
141
+ var Oscillator = class {
142
+ player;
143
+ element;
144
+ id;
145
+ frequency = DEFAULT_OSCILLATOR_PARAMS.frequency;
146
+ volume;
147
+ duration;
148
+ label;
149
+ playbackLabel;
150
+ rendered;
151
+ playbackButton;
152
+ /**
153
+ * Creates an `Oscillator` instance.
154
+ *
155
+ * @param __namedParameters The accepted params
156
+ */
157
+ constructor({
158
+ player,
159
+ element,
160
+ id,
161
+ frequency = DEFAULT_OSCILLATOR_PARAMS.frequency,
162
+ volume = DEFAULT_OSCILLATOR_PARAMS.volume,
163
+ duration = DEFAULT_OSCILLATOR_PARAMS.duration,
164
+ label = DEFAULT_OSCILLATOR_PARAMS.label,
165
+ playbackLabel = DEFAULT_OSCILLATOR_PARAMS.playbackLabel
166
+ }) {
167
+ if (!element) {
168
+ throw new Error("Element not found");
169
+ }
170
+ this.player = player;
171
+ this.element = element;
172
+ this.id = id;
173
+ this.setFrequency(frequency);
174
+ this.volume = volume;
175
+ this.duration = duration;
176
+ this.label = label;
177
+ this.playbackLabel = playbackLabel;
178
+ this.rendered = false;
179
+ this.playbackButton = null;
180
+ player.on("start", ({ id: id2 }) => {
181
+ if (id2 !== this.id) {
182
+ return;
183
+ }
184
+ this.playbackButton.disabled = true;
185
+ });
186
+ player.on("noAvailableVoices", ({ id: id2 }) => {
187
+ if (id2 !== this.id) {
188
+ return;
189
+ }
190
+ this.playbackButton.disabled = false;
191
+ });
192
+ player.on("finished", ({ id: id2 }) => {
193
+ if (id2 !== this.id) {
194
+ return;
195
+ }
196
+ this.playbackButton.disabled = false;
197
+ });
198
+ }
199
+ /**
200
+ * Sets the new frequency value, clamped to the audible frequency bounds.
201
+ * @param frequency The new frequency value
202
+ * @returns The current Oscillator instance
203
+ */
204
+ setFrequency(frequency) {
205
+ const [lowFreq, highFreq] = FREQUENCY_BOUNDS;
206
+ if (frequency < lowFreq) {
207
+ this.frequency = lowFreq;
208
+ console.warn(`Oscillator frequency cannot be lower than ${lowFreq}`);
209
+ return this;
210
+ }
211
+ if (frequency > highFreq) {
212
+ this.frequency = highFreq;
213
+ console.warn(`Oscillator frequency cannot be higher than ${highFreq}`);
214
+ return this;
215
+ }
216
+ this.frequency = frequency;
217
+ return this;
218
+ }
219
+ /**
220
+ * @returns the oscillator frequency
221
+ */
222
+ getFrequency() {
223
+ return this.frequency;
224
+ }
225
+ /**
226
+ * Renders the UI inside the current element.
227
+ * @returns The current Oscillator instance.
228
+ */
229
+ render() {
230
+ if (this.rendered) {
231
+ return this;
232
+ }
233
+ this.baseRender();
234
+ return this;
235
+ }
236
+ onPlay() {
237
+ this.player.play({
238
+ id: this.id,
239
+ frequency: this.frequency,
240
+ duration: this.duration,
241
+ volume: this.volume
242
+ });
243
+ }
244
+ baseRender() {
245
+ const valueElement = document.createElement("div");
246
+ valueElement.classList.add(cssClasses.value);
247
+ valueElement.textContent = this.label ? `${this.frequency} - ${this.label}` : `${this.frequency}`;
248
+ const controlsElement = document.createElement("div");
249
+ controlsElement.classList.add(cssClasses.controls);
250
+ this.playbackButton = document.createElement("button");
251
+ this.playbackButton.textContent = this.playbackLabel;
252
+ this.playbackButton.setAttribute(
253
+ "aria-label",
254
+ `Playback oscillator with frequency: ${this.frequency}`
255
+ );
256
+ this.playbackButton.addEventListener("click", this.onPlay.bind(this));
257
+ controlsElement.appendChild(this.playbackButton);
258
+ this.element.appendChild(valueElement);
259
+ this.element.appendChild(controlsElement);
260
+ this.rendered = true;
261
+ }
262
+ };
263
+
264
+ // src/init.ts
265
+ import {
266
+ ensureSelection,
267
+ extractElementOptions
268
+ } from "@music-ui/core";
269
+ var DEFAULT_OPTIONS = {
270
+ selection: ".oscillator"
271
+ };
272
+ function initOscillator(params = {}) {
273
+ const { selection, player } = { ...DEFAULT_OPTIONS, ...params };
274
+ if (!(player instanceof OscPlayer)) {
275
+ throw new Error("You must pass an OscPlayer instance");
276
+ }
277
+ ensureSelection(selection).forEach((element, index) => {
278
+ new Oscillator({
279
+ player,
280
+ element,
281
+ id: `osc-${index + 1}`,
282
+ ...extractElementOptions(element, DEFAULT_OSCILLATOR_PARAMS)
283
+ }).render();
284
+ });
285
+ }
286
+
287
+ // src/initWithOscilloscope.ts
288
+ import { ensureElements, ensureSelection as ensureSelection2 } from "@music-ui/core";
289
+
290
+ // src/Oscilloscope.ts
291
+ var DEFAULT_AXIS_COLOR = "#1C3A26";
292
+ var DEFAULT_AXIS_WIDTH = 4;
293
+ var DEFAULT_BACKGROUND_COLOR = "#07140C";
294
+ var DEFAULT_WAVEFORM_COLOR = "#86FCA4";
295
+ var DEFAULT_WAVEFORM_WIDTH = 2;
296
+ var Oscilloscope = class {
297
+ element;
298
+ rendered;
299
+ player;
300
+ shouldRefresh;
301
+ canvas;
302
+ resizeObserver;
303
+ axisColor;
304
+ axisStrokeWidth;
305
+ waveFormColor;
306
+ waveFormStrokeWidth;
307
+ backgroundColor;
308
+ /**
309
+ * Creates an `Oscilloscope` instance.
310
+ *
311
+ * @param __namedParameters The accepted params
312
+ */
313
+ constructor({
314
+ element,
315
+ player,
316
+ axisColor = DEFAULT_AXIS_COLOR,
317
+ axisStrokeWidth = DEFAULT_AXIS_WIDTH,
318
+ waveFormColor = DEFAULT_WAVEFORM_COLOR,
319
+ waveFormStrokeWidth = DEFAULT_WAVEFORM_WIDTH,
320
+ backgroundColor = DEFAULT_BACKGROUND_COLOR
321
+ }) {
322
+ this.element = element;
323
+ this.player = player;
324
+ this.rendered = false;
325
+ this.shouldRefresh = false;
326
+ this.canvas = null;
327
+ this.resizeObserver = null;
328
+ this.axisColor = axisColor;
329
+ this.axisStrokeWidth = axisStrokeWidth;
330
+ this.waveFormColor = waveFormColor;
331
+ this.waveFormStrokeWidth = waveFormStrokeWidth;
332
+ this.backgroundColor = backgroundColor;
333
+ this.player.on("start", () => {
334
+ this.shouldRefresh = true;
335
+ this.drawWave();
336
+ });
337
+ this.player.on("allFinished", () => {
338
+ this.shouldRefresh = false;
339
+ this.render();
340
+ });
341
+ }
342
+ /**
343
+ * Renders the oscilloscope inside the current element.
344
+ * @returns The current Oscilloscope instance.
345
+ */
346
+ render() {
347
+ this.baseRender();
348
+ this.resizeCanvas();
349
+ this.drawBackground();
350
+ this.drawAxis();
351
+ return this;
352
+ }
353
+ /**
354
+ * Clears all event listeners
355
+ */
356
+ destroy() {
357
+ this.resizeObserver?.disconnect();
358
+ }
359
+ drawBackground() {
360
+ const canvas = this.canvas;
361
+ const c = canvas.getContext("2d");
362
+ c.fillStyle = this.backgroundColor;
363
+ c.fillRect(0, 0, canvas.width, canvas.height);
364
+ }
365
+ drawAxis() {
366
+ const canvas = this.canvas;
367
+ const c = canvas.getContext("2d");
368
+ c.strokeStyle = this.axisColor;
369
+ c.lineWidth = this.axisStrokeWidth;
370
+ c.beginPath();
371
+ c.moveTo(0, canvas.height / 2);
372
+ c.lineTo(canvas.width, canvas.height / 2);
373
+ c.stroke();
374
+ c.closePath();
375
+ }
376
+ drawWave() {
377
+ const data = this.player.getData();
378
+ const canvas = this.canvas;
379
+ const c = canvas.getContext("2d");
380
+ this.drawBackground();
381
+ this.drawAxis();
382
+ if (!this.shouldRefresh) {
383
+ return;
384
+ }
385
+ c.beginPath();
386
+ c.strokeStyle = this.waveFormColor;
387
+ c.lineWidth = this.waveFormStrokeWidth;
388
+ const segmentWidth = canvas.width / data.length;
389
+ const startIndex = data.findIndex(
390
+ (value, index) => index > 0 && data[index - 1] < 128 && value >= 128
391
+ );
392
+ for (let i = startIndex; i < data.length; i += 1) {
393
+ const x = (i - startIndex) * segmentWidth;
394
+ const v = data[i] / 128;
395
+ const y = v * canvas.height / 2;
396
+ c.lineTo(x, y);
397
+ }
398
+ c.stroke();
399
+ c.closePath();
400
+ requestAnimationFrame(this.drawWave.bind(this));
401
+ }
402
+ resizeCanvas() {
403
+ const { width, height } = this.element.getBoundingClientRect();
404
+ this.canvas.width = width;
405
+ this.canvas.height = height;
406
+ }
407
+ baseRender() {
408
+ if (this.rendered) {
409
+ return;
410
+ }
411
+ this.canvas = document.createElement("canvas");
412
+ this.element.appendChild(this.canvas);
413
+ this.rendered = true;
414
+ if (!this.resizeObserver) {
415
+ this.resizeObserver = new ResizeObserver(this.render.bind(this));
416
+ this.resizeObserver.observe(this.element);
417
+ }
418
+ }
419
+ };
420
+
421
+ // src/initWithOscilloscope.ts
422
+ var cssClasses2 = {
423
+ wrapper: "oscillators-with-oscilloscope",
424
+ oscillators: "oscillators",
425
+ oscillator: "oscillator",
426
+ oscilloscope: "oscilloscope"
427
+ };
428
+ function initOscillatorWithOscilloscope(params) {
429
+ const { selection, player } = {
430
+ selection: cssClasses2.wrapper,
431
+ ...params
432
+ };
433
+ if (!(player instanceof OscPlayer)) {
434
+ throw new Error("You must pass an OscPlayer instance");
435
+ }
436
+ ensureSelection2(selection).forEach((element, index) => {
437
+ const id = element.dataset.id || `${index + 1}`;
438
+ const { oscillatorsElement, oscilloscopeElement } = ensureElements({
439
+ id,
440
+ parentElement: element,
441
+ elements: {
442
+ oscillatorsElement: `.${cssClasses2.oscillators}`,
443
+ oscilloscopeElement: `.${cssClasses2.oscilloscope}`
444
+ }
445
+ });
446
+ initOscillator({
447
+ selection: oscillatorsElement.querySelectorAll(
448
+ `.${cssClasses2.oscillator}`
449
+ ),
450
+ player
451
+ });
452
+ new Oscilloscope({
453
+ element: oscilloscopeElement,
454
+ player
455
+ }).render();
456
+ });
457
+ }
458
+ export {
459
+ DEFAULT_OPTIONS,
460
+ DEFAULT_OSCILLATOR_PARAMS,
461
+ OscPlayer,
462
+ Oscillator,
463
+ cssClasses,
464
+ initOscillator,
465
+ initOscillatorWithOscilloscope
466
+ };
@@ -0,0 +1,7 @@
1
+ /* src/styles/index.css */
2
+ .oscillator {
3
+ display: flex;
4
+ flex-direction: column;
5
+ align-items: center;
6
+ gap: 0.5rem;
7
+ }
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,2 @@
1
+
2
+ export { }