@music-ui/osc 0.17.3 → 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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Music UI - ABC
1
+ # Music UI - Osc
2
2
 
3
- Abc notation rendering utilities.
3
+ Oscillator utilities.
4
4
 
5
5
  ## Installation and usage
6
6
 
package/dist/index.cjs CHANGED
@@ -25,25 +25,42 @@ __export(index_exports, {
25
25
  OscPlayer: () => OscPlayer,
26
26
  Oscillator: () => Oscillator,
27
27
  cssClasses: () => cssClasses,
28
- initOscillator: () => initOscillator
28
+ initOscillator: () => initOscillator,
29
+ initOscillatorWithOscilloscope: () => initOscillatorWithOscilloscope
29
30
  });
30
31
  module.exports = __toCommonJS(index_exports);
31
32
 
32
33
  // src/OscPlayer.ts
33
34
  var import_events = require("events");
34
35
  var DEFAULT_MAX_VOICES = 2;
36
+ var DEFAULT_FADE_IN_TIME = 0.05;
37
+ var DEFAULT_FADE_OUT_TIME = 0.05;
35
38
  var OscPlayer = class {
36
39
  context;
37
40
  eventEmitter;
41
+ analyser;
42
+ data;
38
43
  oscillators;
39
- constructor({ context, voices = DEFAULT_MAX_VOICES }) {
44
+ /**
45
+ * Creates an `OscPlayer` instance.
46
+ *
47
+ * @param __namedParameters The accepted params
48
+ */
49
+ constructor({
50
+ context,
51
+ analyzer,
52
+ voices = DEFAULT_MAX_VOICES
53
+ }) {
40
54
  this.context = context;
41
55
  this.eventEmitter = new import_events.EventEmitter();
56
+ this.analyser = analyzer;
57
+ this.analyser.connect(context.destination);
58
+ this.data = new Uint8Array(this.analyser.frequencyBinCount);
42
59
  this.oscillators = Array.from({ length: voices }, () => {
43
60
  const osc = context.createOscillator();
44
61
  const gain = context.createGain();
45
62
  osc.connect(gain);
46
- gain.connect(context.destination);
63
+ gain.connect(this.analyser);
47
64
  return {
48
65
  playing: false,
49
66
  started: false,
@@ -53,11 +70,57 @@ var OscPlayer = class {
53
70
  };
54
71
  });
55
72
  }
73
+ /**
74
+ * Returns the analyzer data at the current time
75
+ * @returns the analyzer data
76
+ */
77
+ getData() {
78
+ this.analyser.getByteTimeDomainData(this.data);
79
+ return this.data;
80
+ }
81
+ /**
82
+ * @returns the current AudioContext
83
+ */
84
+ getAudioContext() {
85
+ return this.context;
86
+ }
87
+ /**
88
+ * Listens to the passed OscPlayer event
89
+ * @param eventName The event name
90
+ * @param callback The event callback
91
+ * @returns The corresponding unsubscribe function
92
+ */
56
93
  on(eventName, callback) {
57
94
  this.eventEmitter.addListener(eventName, callback);
58
95
  return () => this.eventEmitter.removeListener(eventName, callback);
59
96
  }
60
- play({ id, frequency, duration, volume }) {
97
+ /**
98
+ * Clears all event listeners and future playback scheduled events.
99
+ */
100
+ destroy() {
101
+ this.oscillators.forEach(({ osc, gain, timeout, started }) => {
102
+ gain.disconnect();
103
+ osc.disconnect();
104
+ if (started) {
105
+ osc.stop();
106
+ }
107
+ clearTimeout(timeout);
108
+ });
109
+ this.eventEmitter.removeAllListeners();
110
+ }
111
+ /**
112
+ * Schedules immediate playback.
113
+ * @param __namedParameters The accepted params
114
+ * @returns The current OscPlayer instance
115
+ */
116
+ play({
117
+ id,
118
+ frequency,
119
+ duration,
120
+ volume,
121
+ fadeInTime = DEFAULT_FADE_IN_TIME,
122
+ fadeOutTime = DEFAULT_FADE_OUT_TIME
123
+ }) {
61
124
  if (this.oscillators.every(({ timeout }) => timeout > -1)) {
62
125
  console.warn("All oscillators are already playing");
63
126
  this.eventEmitter.emit("noAvailableVoices", { id });
@@ -70,22 +133,26 @@ var OscPlayer = class {
70
133
  oscillator.started = true;
71
134
  oscillator.osc.start();
72
135
  }
73
- oscillator.gain.gain.setValueAtTime(volume, currentTime);
74
- oscillator.gain.gain.setValueAtTime(0, currentTime + duration);
136
+ oscillator.gain.gain.setValueAtTime(0, currentTime);
137
+ oscillator.gain.gain.linearRampToValueAtTime(
138
+ volume,
139
+ currentTime + fadeInTime
140
+ );
141
+ oscillator.gain.gain.setValueAtTime(
142
+ volume,
143
+ currentTime + duration - fadeOutTime
144
+ );
145
+ oscillator.gain.gain.linearRampToValueAtTime(0, currentTime + duration);
75
146
  this.eventEmitter.emit("start", { id });
76
147
  oscillator.timeout = setTimeout(() => {
77
148
  oscillator.timeout = -1;
78
149
  this.eventEmitter.emit("finished", { id });
150
+ if (this.oscillators.some(({ timeout }) => timeout === -1)) {
151
+ return;
152
+ }
153
+ this.eventEmitter.emit("allFinished");
79
154
  }, duration * 1e3);
80
- }
81
- destroy() {
82
- this.oscillators.forEach(({ osc, gain, timeout }) => {
83
- gain.disconnect();
84
- osc.disconnect();
85
- osc.stop();
86
- clearTimeout(timeout);
87
- });
88
- this.eventEmitter.removeAllListeners();
155
+ return this;
89
156
  }
90
157
  };
91
158
 
@@ -98,7 +165,7 @@ var cssClasses = {
98
165
  };
99
166
  var DEFAULT_OSCILLATOR_PARAMS = {
100
167
  frequency: 440,
101
- volume: -6,
168
+ volume: 0.5,
102
169
  duration: 1,
103
170
  label: "",
104
171
  playbackLabel: "Play"
@@ -114,6 +181,11 @@ var Oscillator = class {
114
181
  playbackLabel;
115
182
  rendered;
116
183
  playbackButton;
184
+ /**
185
+ * Creates an `Oscillator` instance.
186
+ *
187
+ * @param __namedParameters The accepted params
188
+ */
117
189
  constructor({
118
190
  player,
119
191
  element,
@@ -156,6 +228,11 @@ var Oscillator = class {
156
228
  this.playbackButton.disabled = false;
157
229
  });
158
230
  }
231
+ /**
232
+ * Sets the new frequency value, clamped to the audible frequency bounds.
233
+ * @param frequency The new frequency value
234
+ * @returns The current Oscillator instance
235
+ */
159
236
  setFrequency(frequency) {
160
237
  const [lowFreq, highFreq] = FREQUENCY_BOUNDS;
161
238
  if (frequency < lowFreq) {
@@ -171,6 +248,9 @@ var Oscillator = class {
171
248
  this.frequency = frequency;
172
249
  return this;
173
250
  }
251
+ /**
252
+ * @returns the oscillator frequency
253
+ */
174
254
  getFrequency() {
175
255
  return this.frequency;
176
256
  }
@@ -216,7 +296,7 @@ var Oscillator = class {
216
296
  // src/init.ts
217
297
  var import_core = require("@music-ui/core");
218
298
  var DEFAULT_OPTIONS = {
219
- selection: "[data-oscillator]"
299
+ selection: ".oscillator"
220
300
  };
221
301
  function initOscillator(params = {}) {
222
302
  const { selection, player } = { ...DEFAULT_OPTIONS, ...params };
@@ -232,6 +312,178 @@ function initOscillator(params = {}) {
232
312
  }).render();
233
313
  });
234
314
  }
315
+
316
+ // src/initWithOscilloscope.ts
317
+ var import_core2 = require("@music-ui/core");
318
+
319
+ // src/Oscilloscope.ts
320
+ var DEFAULT_AXIS_COLOR = "#1C3A26";
321
+ var DEFAULT_AXIS_WIDTH = 4;
322
+ var DEFAULT_BACKGROUND_COLOR = "#07140C";
323
+ var DEFAULT_WAVEFORM_COLOR = "#86FCA4";
324
+ var DEFAULT_WAVEFORM_WIDTH = 2;
325
+ var Oscilloscope = class {
326
+ element;
327
+ rendered;
328
+ player;
329
+ shouldRefresh;
330
+ canvas;
331
+ resizeObserver;
332
+ axisColor;
333
+ axisStrokeWidth;
334
+ waveFormColor;
335
+ waveFormStrokeWidth;
336
+ backgroundColor;
337
+ /**
338
+ * Creates an `Oscilloscope` instance.
339
+ *
340
+ * @param __namedParameters The accepted params
341
+ */
342
+ constructor({
343
+ element,
344
+ player,
345
+ axisColor = DEFAULT_AXIS_COLOR,
346
+ axisStrokeWidth = DEFAULT_AXIS_WIDTH,
347
+ waveFormColor = DEFAULT_WAVEFORM_COLOR,
348
+ waveFormStrokeWidth = DEFAULT_WAVEFORM_WIDTH,
349
+ backgroundColor = DEFAULT_BACKGROUND_COLOR
350
+ }) {
351
+ this.element = element;
352
+ this.player = player;
353
+ this.rendered = false;
354
+ this.shouldRefresh = false;
355
+ this.canvas = null;
356
+ this.resizeObserver = null;
357
+ this.axisColor = axisColor;
358
+ this.axisStrokeWidth = axisStrokeWidth;
359
+ this.waveFormColor = waveFormColor;
360
+ this.waveFormStrokeWidth = waveFormStrokeWidth;
361
+ this.backgroundColor = backgroundColor;
362
+ this.player.on("start", () => {
363
+ this.shouldRefresh = true;
364
+ this.drawWave();
365
+ });
366
+ this.player.on("allFinished", () => {
367
+ this.shouldRefresh = false;
368
+ this.render();
369
+ });
370
+ }
371
+ /**
372
+ * Renders the oscilloscope inside the current element.
373
+ * @returns The current Oscilloscope instance.
374
+ */
375
+ render() {
376
+ this.baseRender();
377
+ this.resizeCanvas();
378
+ this.drawBackground();
379
+ this.drawAxis();
380
+ return this;
381
+ }
382
+ /**
383
+ * Clears all event listeners
384
+ */
385
+ destroy() {
386
+ this.resizeObserver?.disconnect();
387
+ }
388
+ drawBackground() {
389
+ const canvas = this.canvas;
390
+ const c = canvas.getContext("2d");
391
+ c.fillStyle = this.backgroundColor;
392
+ c.fillRect(0, 0, canvas.width, canvas.height);
393
+ }
394
+ drawAxis() {
395
+ const canvas = this.canvas;
396
+ const c = canvas.getContext("2d");
397
+ c.strokeStyle = this.axisColor;
398
+ c.lineWidth = this.axisStrokeWidth;
399
+ c.beginPath();
400
+ c.moveTo(0, canvas.height / 2);
401
+ c.lineTo(canvas.width, canvas.height / 2);
402
+ c.stroke();
403
+ c.closePath();
404
+ }
405
+ drawWave() {
406
+ const data = this.player.getData();
407
+ const canvas = this.canvas;
408
+ const c = canvas.getContext("2d");
409
+ this.drawBackground();
410
+ this.drawAxis();
411
+ if (!this.shouldRefresh) {
412
+ return;
413
+ }
414
+ c.beginPath();
415
+ c.strokeStyle = this.waveFormColor;
416
+ c.lineWidth = this.waveFormStrokeWidth;
417
+ const segmentWidth = canvas.width / data.length;
418
+ const startIndex = data.findIndex(
419
+ (value, index) => index > 0 && data[index - 1] < 128 && value >= 128
420
+ );
421
+ for (let i = startIndex; i < data.length; i += 1) {
422
+ const x = (i - startIndex) * segmentWidth;
423
+ const v = data[i] / 128;
424
+ const y = v * canvas.height / 2;
425
+ c.lineTo(x, y);
426
+ }
427
+ c.stroke();
428
+ c.closePath();
429
+ requestAnimationFrame(this.drawWave.bind(this));
430
+ }
431
+ resizeCanvas() {
432
+ const { width, height } = this.element.getBoundingClientRect();
433
+ this.canvas.width = width;
434
+ this.canvas.height = height;
435
+ }
436
+ baseRender() {
437
+ if (this.rendered) {
438
+ return;
439
+ }
440
+ this.canvas = document.createElement("canvas");
441
+ this.element.appendChild(this.canvas);
442
+ this.rendered = true;
443
+ if (!this.resizeObserver) {
444
+ this.resizeObserver = new ResizeObserver(this.render.bind(this));
445
+ this.resizeObserver.observe(this.element);
446
+ }
447
+ }
448
+ };
449
+
450
+ // src/initWithOscilloscope.ts
451
+ var cssClasses2 = {
452
+ wrapper: "oscillators-with-oscilloscope",
453
+ oscillators: "oscillators",
454
+ oscillator: "oscillator",
455
+ oscilloscope: "oscilloscope"
456
+ };
457
+ function initOscillatorWithOscilloscope(params) {
458
+ const { selection, player } = {
459
+ selection: cssClasses2.wrapper,
460
+ ...params
461
+ };
462
+ if (!(player instanceof OscPlayer)) {
463
+ throw new Error("You must pass an OscPlayer instance");
464
+ }
465
+ (0, import_core2.ensureSelection)(selection).forEach((element, index) => {
466
+ const id = element.dataset.id || `${index + 1}`;
467
+ const { oscillatorsElement, oscilloscopeElement } = (0, import_core2.ensureElements)({
468
+ id,
469
+ parentElement: element,
470
+ elements: {
471
+ oscillatorsElement: `.${cssClasses2.oscillators}`,
472
+ oscilloscopeElement: `.${cssClasses2.oscilloscope}`
473
+ }
474
+ });
475
+ initOscillator({
476
+ selection: oscillatorsElement.querySelectorAll(
477
+ `.${cssClasses2.oscillator}`
478
+ ),
479
+ player
480
+ });
481
+ new Oscilloscope({
482
+ element: oscilloscopeElement,
483
+ player
484
+ }).render();
485
+ });
486
+ }
235
487
  // Annotate the CommonJS export names for ESM import in node:
236
488
  0 && (module.exports = {
237
489
  DEFAULT_OPTIONS,
@@ -239,5 +491,6 @@ function initOscillator(params = {}) {
239
491
  OscPlayer,
240
492
  Oscillator,
241
493
  cssClasses,
242
- initOscillator
494
+ initOscillator,
495
+ initOscillatorWithOscilloscope
243
496
  });
package/dist/index.d.cts CHANGED
@@ -4,7 +4,7 @@ import { ElementOrSelector } from '@music-ui/core';
4
4
  /**
5
5
  * The events triggered by the player.
6
6
  */
7
- type OscPlayerEvents = "start" | "finished" | "noAvailableVoices";
7
+ type OscPlayerEvents = "start" | "finished" | "noAvailableVoices" | "allFinished";
8
8
  /**
9
9
  * The osc player event listener callback.
10
10
  * @property id The current osc id.
@@ -12,24 +12,72 @@ type OscPlayerEvents = "start" | "finished" | "noAvailableVoices";
12
12
  type OscPlayerCallback = (params: {
13
13
  id: string;
14
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
+ */
15
21
  type OscPlayerConstructors = {
16
22
  context: AudioContext;
23
+ analyzer: AnalyserNode;
17
24
  voices?: number;
18
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
+ */
19
35
  type OscPlayParams = {
20
36
  id: string;
21
37
  frequency: number;
22
38
  duration: number;
23
39
  volume: number;
40
+ fadeInTime?: number;
41
+ fadeOutTime?: number;
24
42
  };
25
43
  declare class OscPlayer {
26
44
  private context;
27
45
  private eventEmitter;
46
+ private analyser;
47
+ private data;
28
48
  private oscillators;
29
- constructor({ context, voices }: OscPlayerConstructors);
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
+ */
30
70
  on(eventName: OscPlayerEvents, callback: OscPlayerCallback): () => EventEmitter;
31
- play({ id, frequency, duration, volume }: OscPlayParams): void;
71
+ /**
72
+ * Clears all event listeners and future playback scheduled events.
73
+ */
32
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;
33
81
  }
34
82
 
35
83
  /**
@@ -44,11 +92,22 @@ declare const cssClasses: {
44
92
  };
45
93
  declare const DEFAULT_OSCILLATOR_PARAMS: {
46
94
  readonly frequency: 440;
47
- readonly volume: -6;
95
+ readonly volume: 0.5;
48
96
  readonly duration: 1;
49
97
  readonly label: "";
50
98
  readonly playbackLabel: "Play";
51
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
+ */
52
111
  type OscillatorParams = {
53
112
  player: OscPlayer;
54
113
  element: HTMLElement;
@@ -70,8 +129,21 @@ declare class Oscillator {
70
129
  private playbackLabel;
71
130
  private rendered;
72
131
  private playbackButton;
132
+ /**
133
+ * Creates an `Oscillator` instance.
134
+ *
135
+ * @param __namedParameters The accepted params
136
+ */
73
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
+ */
74
143
  setFrequency(frequency: number): Oscillator;
144
+ /**
145
+ * @returns the oscillator frequency
146
+ */
75
147
  getFrequency(): number;
76
148
  /**
77
149
  * Renders the UI inside the current element.
@@ -91,7 +163,7 @@ type InitOscillatorParams<T extends HTMLElement> = {
91
163
  player: OscPlayer;
92
164
  };
93
165
  declare const DEFAULT_OPTIONS: {
94
- readonly selection: "[data-oscillator]";
166
+ readonly selection: ".oscillator";
95
167
  };
96
168
  /**
97
169
  * Initializes oscillators on the passed selection.
@@ -99,4 +171,15 @@ declare const DEFAULT_OPTIONS: {
99
171
  */
100
172
  declare function initOscillator<T extends HTMLElement>(params?: Partial<InitOscillatorParams<T>>): void;
101
173
 
102
- export { DEFAULT_OPTIONS, DEFAULT_OSCILLATOR_PARAMS, type InitOscillatorParams, OscPlayer, type OscPlayerCallback, type OscPlayerEvents, Oscillator, type OscillatorParams, cssClasses, initOscillator };
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.d.ts CHANGED
@@ -4,7 +4,7 @@ import { ElementOrSelector } from '@music-ui/core';
4
4
  /**
5
5
  * The events triggered by the player.
6
6
  */
7
- type OscPlayerEvents = "start" | "finished" | "noAvailableVoices";
7
+ type OscPlayerEvents = "start" | "finished" | "noAvailableVoices" | "allFinished";
8
8
  /**
9
9
  * The osc player event listener callback.
10
10
  * @property id The current osc id.
@@ -12,24 +12,72 @@ type OscPlayerEvents = "start" | "finished" | "noAvailableVoices";
12
12
  type OscPlayerCallback = (params: {
13
13
  id: string;
14
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
+ */
15
21
  type OscPlayerConstructors = {
16
22
  context: AudioContext;
23
+ analyzer: AnalyserNode;
17
24
  voices?: number;
18
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
+ */
19
35
  type OscPlayParams = {
20
36
  id: string;
21
37
  frequency: number;
22
38
  duration: number;
23
39
  volume: number;
40
+ fadeInTime?: number;
41
+ fadeOutTime?: number;
24
42
  };
25
43
  declare class OscPlayer {
26
44
  private context;
27
45
  private eventEmitter;
46
+ private analyser;
47
+ private data;
28
48
  private oscillators;
29
- constructor({ context, voices }: OscPlayerConstructors);
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
+ */
30
70
  on(eventName: OscPlayerEvents, callback: OscPlayerCallback): () => EventEmitter;
31
- play({ id, frequency, duration, volume }: OscPlayParams): void;
71
+ /**
72
+ * Clears all event listeners and future playback scheduled events.
73
+ */
32
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;
33
81
  }
34
82
 
35
83
  /**
@@ -44,11 +92,22 @@ declare const cssClasses: {
44
92
  };
45
93
  declare const DEFAULT_OSCILLATOR_PARAMS: {
46
94
  readonly frequency: 440;
47
- readonly volume: -6;
95
+ readonly volume: 0.5;
48
96
  readonly duration: 1;
49
97
  readonly label: "";
50
98
  readonly playbackLabel: "Play";
51
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
+ */
52
111
  type OscillatorParams = {
53
112
  player: OscPlayer;
54
113
  element: HTMLElement;
@@ -70,8 +129,21 @@ declare class Oscillator {
70
129
  private playbackLabel;
71
130
  private rendered;
72
131
  private playbackButton;
132
+ /**
133
+ * Creates an `Oscillator` instance.
134
+ *
135
+ * @param __namedParameters The accepted params
136
+ */
73
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
+ */
74
143
  setFrequency(frequency: number): Oscillator;
144
+ /**
145
+ * @returns the oscillator frequency
146
+ */
75
147
  getFrequency(): number;
76
148
  /**
77
149
  * Renders the UI inside the current element.
@@ -91,7 +163,7 @@ type InitOscillatorParams<T extends HTMLElement> = {
91
163
  player: OscPlayer;
92
164
  };
93
165
  declare const DEFAULT_OPTIONS: {
94
- readonly selection: "[data-oscillator]";
166
+ readonly selection: ".oscillator";
95
167
  };
96
168
  /**
97
169
  * Initializes oscillators on the passed selection.
@@ -99,4 +171,15 @@ declare const DEFAULT_OPTIONS: {
99
171
  */
100
172
  declare function initOscillator<T extends HTMLElement>(params?: Partial<InitOscillatorParams<T>>): void;
101
173
 
102
- export { DEFAULT_OPTIONS, DEFAULT_OSCILLATOR_PARAMS, type InitOscillatorParams, OscPlayer, type OscPlayerCallback, type OscPlayerEvents, Oscillator, type OscillatorParams, cssClasses, initOscillator };
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 CHANGED
@@ -1,18 +1,34 @@
1
1
  // src/OscPlayer.ts
2
2
  import { EventEmitter } from "events";
3
3
  var DEFAULT_MAX_VOICES = 2;
4
+ var DEFAULT_FADE_IN_TIME = 0.05;
5
+ var DEFAULT_FADE_OUT_TIME = 0.05;
4
6
  var OscPlayer = class {
5
7
  context;
6
8
  eventEmitter;
9
+ analyser;
10
+ data;
7
11
  oscillators;
8
- constructor({ context, voices = DEFAULT_MAX_VOICES }) {
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
+ }) {
9
22
  this.context = context;
10
23
  this.eventEmitter = new EventEmitter();
24
+ this.analyser = analyzer;
25
+ this.analyser.connect(context.destination);
26
+ this.data = new Uint8Array(this.analyser.frequencyBinCount);
11
27
  this.oscillators = Array.from({ length: voices }, () => {
12
28
  const osc = context.createOscillator();
13
29
  const gain = context.createGain();
14
30
  osc.connect(gain);
15
- gain.connect(context.destination);
31
+ gain.connect(this.analyser);
16
32
  return {
17
33
  playing: false,
18
34
  started: false,
@@ -22,11 +38,57 @@ var OscPlayer = class {
22
38
  };
23
39
  });
24
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
+ */
25
61
  on(eventName, callback) {
26
62
  this.eventEmitter.addListener(eventName, callback);
27
63
  return () => this.eventEmitter.removeListener(eventName, callback);
28
64
  }
29
- play({ id, frequency, duration, volume }) {
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
+ }) {
30
92
  if (this.oscillators.every(({ timeout }) => timeout > -1)) {
31
93
  console.warn("All oscillators are already playing");
32
94
  this.eventEmitter.emit("noAvailableVoices", { id });
@@ -39,22 +101,26 @@ var OscPlayer = class {
39
101
  oscillator.started = true;
40
102
  oscillator.osc.start();
41
103
  }
42
- oscillator.gain.gain.setValueAtTime(volume, currentTime);
43
- oscillator.gain.gain.setValueAtTime(0, currentTime + duration);
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);
44
114
  this.eventEmitter.emit("start", { id });
45
115
  oscillator.timeout = setTimeout(() => {
46
116
  oscillator.timeout = -1;
47
117
  this.eventEmitter.emit("finished", { id });
118
+ if (this.oscillators.some(({ timeout }) => timeout === -1)) {
119
+ return;
120
+ }
121
+ this.eventEmitter.emit("allFinished");
48
122
  }, duration * 1e3);
49
- }
50
- destroy() {
51
- this.oscillators.forEach(({ osc, gain, timeout }) => {
52
- gain.disconnect();
53
- osc.disconnect();
54
- osc.stop();
55
- clearTimeout(timeout);
56
- });
57
- this.eventEmitter.removeAllListeners();
123
+ return this;
58
124
  }
59
125
  };
60
126
 
@@ -67,7 +133,7 @@ var cssClasses = {
67
133
  };
68
134
  var DEFAULT_OSCILLATOR_PARAMS = {
69
135
  frequency: 440,
70
- volume: -6,
136
+ volume: 0.5,
71
137
  duration: 1,
72
138
  label: "",
73
139
  playbackLabel: "Play"
@@ -83,6 +149,11 @@ var Oscillator = class {
83
149
  playbackLabel;
84
150
  rendered;
85
151
  playbackButton;
152
+ /**
153
+ * Creates an `Oscillator` instance.
154
+ *
155
+ * @param __namedParameters The accepted params
156
+ */
86
157
  constructor({
87
158
  player,
88
159
  element,
@@ -125,6 +196,11 @@ var Oscillator = class {
125
196
  this.playbackButton.disabled = false;
126
197
  });
127
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
+ */
128
204
  setFrequency(frequency) {
129
205
  const [lowFreq, highFreq] = FREQUENCY_BOUNDS;
130
206
  if (frequency < lowFreq) {
@@ -140,6 +216,9 @@ var Oscillator = class {
140
216
  this.frequency = frequency;
141
217
  return this;
142
218
  }
219
+ /**
220
+ * @returns the oscillator frequency
221
+ */
143
222
  getFrequency() {
144
223
  return this.frequency;
145
224
  }
@@ -188,7 +267,7 @@ import {
188
267
  extractElementOptions
189
268
  } from "@music-ui/core";
190
269
  var DEFAULT_OPTIONS = {
191
- selection: "[data-oscillator]"
270
+ selection: ".oscillator"
192
271
  };
193
272
  function initOscillator(params = {}) {
194
273
  const { selection, player } = { ...DEFAULT_OPTIONS, ...params };
@@ -204,11 +283,184 @@ function initOscillator(params = {}) {
204
283
  }).render();
205
284
  });
206
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
+ }
207
458
  export {
208
459
  DEFAULT_OPTIONS,
209
460
  DEFAULT_OSCILLATOR_PARAMS,
210
461
  OscPlayer,
211
462
  Oscillator,
212
463
  cssClasses,
213
- initOscillator
464
+ initOscillator,
465
+ initOscillatorWithOscilloscope
214
466
  };
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "music",
7
7
  "oscillator"
8
8
  ],
9
- "version": "0.17.3",
9
+ "version": "0.18.0",
10
10
  "type": "module",
11
11
  "main": "./dist/index.cjs",
12
12
  "module": "./dist/index.js",
@@ -30,18 +30,19 @@
30
30
  "@testing-library/dom": "^10.4.1",
31
31
  "@testing-library/user-event": "^14.6.1",
32
32
  "@types/events": "^3.0.3",
33
- "@vitest/coverage-istanbul": "4.1.10",
33
+ "@vitest/coverage-istanbul": "5.1.2",
34
34
  "eslint": "^9.39.1",
35
35
  "jsdom": "^30.0.1",
36
36
  "tsup": "^8.5.1",
37
37
  "typescript": "5.9.2",
38
- "vitest": "^4.1.10",
39
- "@music-ui/typescript-config": "0.0.0",
40
- "@music-ui/eslint-config": "0.0.0"
38
+ "vitest": "^5.1.2",
39
+ "vitest-canvas-mock": "^1.2.0",
40
+ "@music-ui/eslint-config": "0.0.0",
41
+ "@music-ui/typescript-config": "0.0.0"
41
42
  },
42
43
  "dependencies": {
43
44
  "events": "^3.3.0",
44
- "@music-ui/core": "0.17.1"
45
+ "@music-ui/core": "0.17.2"
45
46
  },
46
47
  "scripts": {
47
48
  "test": "vitest run",