@grame/faustwasm 0.11.3 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,201 +1,69 @@
1
- // Set to > 0 if the DSP is polyphonic
2
- const FAUST_DSP_VOICES = 0;
3
-
4
- /**
5
- * @typedef {import("./faustwasm").FaustAudioWorkletNode} FaustAudioWorkletNode
6
- * @typedef {import("./faustwasm").FaustDspMeta} FaustDspMeta
7
- * @typedef {import("./faustwasm").FaustUIDescriptor} FaustUIDescriptor
8
- * @typedef {import("./faustwasm").FaustUIGroup} FaustUIGroup
9
- * @typedef {import("./faustwasm").FaustUIItem} FaustUIItem
10
- */
11
1
 
12
2
  /**
13
- * Registers the service worker.
3
+ * @file index-pwa.js
4
+ * Entry point for initializing and managing the Faust PWA instance.
5
+ *
6
+ * ## Overview
7
+ * This script dynamically imports {@link createFaustPWA} from `faust-pwa.js`,
8
+ * creates the Faust PWA controller, and manages user-activation of the
9
+ * Web Audio API (click/touch) as well as visibility-based suspension.
10
+ *
11
+ * ## Responsibilities
12
+ * - Dynamically import `createFaustPWA` (ES module)
13
+ * - Create the PWA instance for the selected DSP
14
+ * - Resume/suspend AudioContext on user interaction or page visibility changes
15
+ * - Activate/deactivate MIDI and sensors
16
+ *
17
+ * ## Emitted Events (from FaustPWA)
18
+ * - `created` — DSP and UI successfully initialized
19
+ * - `started` — Audio, MIDI, and sensors activated
20
+ * - `stopped` — Audio, MIDI, and sensors deactivated
21
+ * - `destroy` — Resources released
22
+ * - `error` — Operational error; see event.detail.error
23
+ *
24
+ * @module index-pwa
14
25
  */
15
- if ("serviceWorker" in navigator) {
16
- window.addEventListener("load", () => {
17
- navigator.serviceWorker.register("./service-worker.js")
18
- .then(reg => console.log("Service Worker registered", reg))
19
- .catch(err => console.log("Service Worker registration failed", err));
20
- });
21
- }
22
26
 
23
- /** @type {HTMLDivElement} */
24
- const $divFaustUI = document.getElementById("div-faust-ui");
25
-
26
- /** @type {typeof AudioContext} */
27
- const AudioCtx = window.AudioContext || window.webkitAudioContext;
28
- const audioContext = new AudioCtx({ latencyHint: 0.00001 });
29
- audioContext.destination.channelInterpretation = "discrete";
30
- audioContext.suspend();
31
-
32
- // Declare faustNode as a global variable
33
- let faustNode;
27
+ // Set to > 0 if the DSP is polyphonic
28
+ const FAUST_DSP_VOICES = 0;
34
29
 
35
- // Called at load time
36
30
  (async () => {
37
31
 
38
- // Import the create-node module
39
- const { createFaustNode, createFaustUI } = await import("./create-node.js");
32
+ const { FaustPWA } = await import("./faust-pwa.js");
40
33
 
41
- // To test the ScriptProcessorNode mode
42
- // const result = await createFaustNode(audioContext, "FAUST_DSP_NAME", FAUST_DSP_VOICES, true, 512);
43
- const result = await createFaustNode(audioContext, "FAUST_DSP_NAME", FAUST_DSP_VOICES);
44
- faustNode = result.faustNode; // Assign to the global variable
45
- if (!faustNode) throw new Error("Faust DSP not compiled");
34
+ /** @type {HTMLDivElement} */
35
+ const divFaustUI = document.getElementById("div-faust-ui");
46
36
 
47
- // Create the Faust UI
48
- await createFaustUI($divFaustUI, faustNode);
37
+ // Declare faustNode as a global variable
38
+ const pwa = new FaustPWA({ dspName: "FAUST_DSP_NAME", voices: FAUST_DSP_VOICES, uiContainer: divFaustUI });
49
39
 
50
- })();
40
+ // Create PWA and UI
41
+ await pwa.create();
51
42
 
52
- // Synchronous function to resume AudioContext, to be called first in the synchronous event listener
53
- function resumeAudioContext() {
54
- if (audioContext.state === 'suspended') {
55
- audioContext.resume().then(() => {
56
- console.log('AudioContext resumed successfully');
57
- }).catch(error => {
58
- console.error('Error when resuming AudioContext:', error);
59
- });
60
- }
61
- }
43
+ // Event listener to handle user interaction
44
+ function handleUserInteraction() {
62
45
 
63
- // Function to start MIDI
64
- function startMIDI() {
65
- // Check if the browser supports the Web MIDI API
66
- if (navigator.requestMIDIAccess) {
67
- navigator.requestMIDIAccess().then(
68
- midiAccess => {
69
- console.log("MIDI Access obtained.");
70
- for (let input of midiAccess.inputs.values()) {
71
- input.onmidimessage = (event) => faustNode.midiMessage(event.data);
72
- console.log(`Connected to input: ${input.name}`);
73
- }
74
- },
75
- () => console.error("Failed to access MIDI devices.")
76
- );
77
- } else {
78
- console.log("Web MIDI API is not supported in this browser.");
79
- }
80
- }
46
+ // Resume AudioContext synchronously
47
+ pwa.resumeAudioContext();
81
48
 
82
- // Function to stop MIDI
83
- function stopMIDI() {
84
- // Check if the browser supports the Web MIDI API
85
- if (navigator.requestMIDIAccess) {
86
- navigator.requestMIDIAccess().then(
87
- midiAccess => {
88
- console.log("MIDI Access obtained.");
89
- for (let input of midiAccess.inputs.values()) {
90
- input.onmidimessage = null;
91
- console.log(`Disconnected from input: ${input.name}`);
92
- }
93
- },
94
- () => console.error("Failed to access MIDI devices.")
95
- );
96
- } else {
97
- console.log("Web MIDI API is not supported in this browser.");
49
+ // Activate MIDI and Sensors
50
+ pwa.activateMIDISensors()
98
51
  }
99
- }
100
-
101
- let sensorHandlersBound = false;
102
- let midiHandlersBound = false;
103
-
104
- // Keyboard to MIDI handing
105
- let keyboard2MIDI = null;
106
-
107
- async function startKeyboard2MIDI() {
108
- // Import the create-node module
109
- const { createKey2MIDI } = await import("./create-node.js");
110
52
 
111
- keyboard2MIDI = createKey2MIDI((event) => faustNode.midiMessage(event));
112
- keyboard2MIDI.start();
113
- }
53
+ // Activate AudioContext, MIDI and Sensors on user interaction
54
+ window.addEventListener('click', handleUserInteraction);
55
+ window.addEventListener('touchstart', handleUserInteraction);
114
56
 
115
- function stopKeyboard2MIDI() {
116
- keyboard2MIDI.stop();
117
- keyboard2MIDI = null;
118
- }
57
+ // Deactivate AudioContext, MIDI and Sensors on user interaction
58
+ window.addEventListener('visibilitychange', function () {
59
+ if (window.visibilityState === 'hidden') {
119
60
 
120
- // Function to activate MIDI and Sensors on user interaction
121
- async function activateMIDISensors() {
61
+ // Suspend AudioContext
62
+ pwa.suspendAudioContext();
122
63
 
123
- // Import the create-node module
124
- const { connectToAudioInput, requestPermissions } = await import("./create-node.js");
125
-
126
- // Request permission for sensors
127
- await requestPermissions();
128
-
129
- // Activate sensor listeners
130
- if (!sensorHandlersBound) {
131
- await faustNode.startSensors();
132
- sensorHandlersBound = true;
133
- }
134
-
135
- // Initialize the MIDI setup
136
- if (!midiHandlersBound) {
137
- startMIDI();
138
- await startKeyboard2MIDI();
139
- midiHandlersBound = true;
140
- }
141
-
142
- // Connect the Faust node to the audio output
143
- faustNode.connect(audioContext.destination);
144
-
145
- // Connect the Faust node to the audio input
146
- if (faustNode.numberOfInputs > 0) {
147
- await connectToAudioInput(audioContext, null, faustNode, null);
148
- }
149
-
150
- // Resume the AudioContext
151
- if (audioContext.state === 'suspended') {
152
- await audioContext.resume();
153
- }
154
- }
155
-
156
- // Function to suspend AudioContext, deactivate MIDI and Sensors on user interaction
157
- async function deactivateAudioMIDISensors() {
158
-
159
- // Suspend the AudioContext
160
- if (audioContext.state === 'running') {
161
- await audioContext.suspend();
162
- }
163
-
164
- // Deactivate sensor listeners
165
- if (sensorHandlersBound) {
166
- faustNode.stopSensors();
167
- sensorHandlersBound = false;
168
- }
169
-
170
- // Deactivate the MIDI setup
171
- if (midiHandlersBound && FAUST_DSP_VOICES > 0) {
172
- stopMIDI();
173
- stopKeyboard2MIDI();
174
- midiHandlersBound = false;
175
- }
176
- }
177
-
178
- // Event listener to handle user interaction
179
- function handleUserInteraction() {
180
-
181
- // Resume AudioContext synchronously
182
- resumeAudioContext();
183
-
184
- // Launch the activation of MIDI and Sensors
185
- activateMIDISensors().catch(error => {
186
- console.error('Error when activating audio, MIDI and sensors:', error);
64
+ // Deactivate MIDI and Sensors
65
+ pwa.deactivateMIDISensors();
66
+ }
187
67
  });
188
- }
189
-
190
- // Activate AudioContext, MIDI and Sensors on user interaction
191
- window.addEventListener('click', handleUserInteraction);
192
- window.addEventListener('touchstart', handleUserInteraction);
193
-
194
- // Deactivate AudioContext, MIDI and Sensors on user interaction
195
- window.addEventListener('visibilitychange', function () {
196
- if (window.visibilityState === 'hidden') {
197
- deactivateAudioMIDISensors();
198
- }
199
- });
200
-
201
68
 
69
+ })();