speaker-calibration 2.2.225 → 2.2.227

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "speaker-calibration",
3
- "version": "2.2.225",
3
+ "version": "2.2.227",
4
4
  "description": "Speaker calibration library for auditory testing",
5
5
  "main": "dist/main.js",
6
6
  "directories": {
@@ -0,0 +1,462 @@
1
+ import {phrases} from '../../dist/example/i18n.js';
2
+ import Listener from '../peer-connection/listener.js';
3
+
4
+ export class PhonePeer {
5
+ constructor() {
6
+ this.phrases = phrases;
7
+ this.name = 'SoundCalibration';
8
+ this.listenerParameters = {
9
+ targetElementId: 'display',
10
+ microphoneFromAPI: '',
11
+ microphoneDeviceId: '',
12
+ };
13
+ this.listener = null;
14
+ this.connectionManager = null;
15
+ }
16
+
17
+ register = manager => {
18
+ this.connectionManager = manager;
19
+ };
20
+
21
+ onMessage = (data, manager) => {
22
+ if (!data || !data.message) return;
23
+
24
+ switch (data.message) {
25
+ case 'connectionParams':
26
+ console.log('connectionParams', data.payload);
27
+ this.handleConnectionParams(data.payload);
28
+ break;
29
+ }
30
+ };
31
+
32
+ handleConnectionParams = async payload => {
33
+ this.isSmartPhone = payload.sp;
34
+ this.listenerParameters.speakerPeerId = payload.speakerPeerId;
35
+ this.listenerParameters.hz = payload.hz;
36
+ this.listenerParameters.bits = payload.bits;
37
+ this.listenerParameters.lang = payload.lang;
38
+ this.listenerParameters.deviceId = payload.deviceId;
39
+ this.listenerParameters.sp = payload.sp;
40
+ this.listenerParameters.microphoneDeviceId = payload.deviceId;
41
+
42
+ this.handleStartCalibration();
43
+ };
44
+
45
+ createUI = () => {
46
+ const container = document.createElement('div');
47
+ container.id = 'listenerContainer';
48
+ container.className = 'container';
49
+ container.innerHTML = `
50
+ <p id="turnMeToReadBelow"></p>
51
+ <div id="updateDisplay">
52
+ <h1 id="recordingInProgress"></h1>
53
+ <p id="allowMicrophone"></p>
54
+ <button id="calibrationBeginButton" class="btn btn-success">Proceed</button>
55
+ </div>
56
+ <div id="display"></div>
57
+ <div id="message"></div>
58
+ <div id="phrases"></div>
59
+ `;
60
+ const target = document.getElementById('target');
61
+ if (target) {
62
+ console.log('target found');
63
+ //clear the target
64
+ target.innerHTML = '';
65
+ target.appendChild(container);
66
+ } else {
67
+ console.log('target not found');
68
+ //create a new target
69
+ const newTarget = document.createElement('div');
70
+ newTarget.id = 'target';
71
+ document.body.appendChild(newTarget);
72
+ newTarget.appendChild(container);
73
+ }
74
+ console.log('UI created');
75
+ };
76
+
77
+ handleStartCalibration = async () => {
78
+ this.createUI();
79
+ if (this.isSmartPhone) {
80
+ await this.initializeSmartPhoneMode();
81
+ } else {
82
+ await this.initializeDesktopMode();
83
+ }
84
+ };
85
+
86
+ initializeListener = async () => {
87
+ this.listener = new Listener(this.listenerParameters);
88
+ this.listener.connectionManager = this.connectionManager;
89
+ };
90
+
91
+ waitForConnection = async (timeout = 30000) => {
92
+ const startTime = Date.now();
93
+
94
+ while (Date.now() - startTime < timeout) {
95
+ if (
96
+ this.listener.connectionManager.peer.id !== null &&
97
+ this.listener.connectionManager.conn !== null &&
98
+ this.listener.connectionManager.connOpen
99
+ ) {
100
+ console.log('Connection established successfully');
101
+ return true;
102
+ }
103
+ console.log('Waiting for connection setup...');
104
+ await new Promise(resolve => setTimeout(resolve, 100));
105
+ }
106
+
107
+ console.error('Connection setup timed out after 30 seconds');
108
+ return false;
109
+ };
110
+
111
+ initializeSmartPhoneMode = async () => {
112
+ // Hide target element
113
+ const targetElement = document.getElementById('display');
114
+ targetElement.style.display = 'none';
115
+
116
+ // Initialize listener
117
+ await this.initializeListener();
118
+
119
+ if (await this.waitForConnection()) {
120
+ await this.checkAndRequestMicrophonePermission();
121
+ } else {
122
+ const allowMicrophoneElement = document.getElementById('allowMicrophone');
123
+ allowMicrophoneElement.innerText = this.phrases.RC_microphonePermissionDenied['en-US'];
124
+ this.listener.sendPermissionStatus({
125
+ type: 'error',
126
+ error: 'Connection setup timed out after 30 seconds',
127
+ });
128
+ }
129
+ };
130
+
131
+ checkAndRequestMicrophonePermission = async () => {
132
+ const container = document.getElementById('listenerContainer');
133
+ const allowMicrophoneElement = document.getElementById('allowMicrophone');
134
+
135
+ // Show permission request message
136
+ allowMicrophoneElement.innerText = this.phrases.RC_microphonePermission['en-US'];
137
+ container.style.display = 'block';
138
+
139
+ // Function to request microphone access
140
+ const requestMicAccess = async (attempt = 1) => {
141
+ try {
142
+ await navigator.mediaDevices.getUserMedia({audio: true});
143
+ // Permission granted, proceed to normal flow
144
+ this.initializeSmartPhoneDisplay();
145
+ } catch (err) {
146
+ if (err.name === 'NotAllowedError') {
147
+ console.log('Permission explicitly denied');
148
+ // Permission explicitly denied
149
+ allowMicrophoneElement.innerText = this.phrases.RC_microphonePermissionDenied['en-US'];
150
+ // Send denied status and end study
151
+ let error = JSON.stringify(err);
152
+ this.listener.sendPermissionStatus({type: 'denied', error: error});
153
+ return;
154
+ }
155
+
156
+ // If 10 seconds passed, try again
157
+ if (attempt < 3) {
158
+ console.log('Retrying microphone access');
159
+ // Limit retries
160
+ setTimeout(() => requestMicAccess(attempt + 1), 10000);
161
+ } else {
162
+ console.log('All retries failed, treating as denied');
163
+ // After all retries failed, treat as denied
164
+ allowMicrophoneElement.innerText = this.phrases.RC_microphonePermissionDenied['en-US'];
165
+ let error = JSON.stringify(err);
166
+ this.listener.sendPermissionStatus({type: 'error', error: error});
167
+ }
168
+ }
169
+ };
170
+
171
+ try {
172
+ await requestMicAccess();
173
+ } catch (err) {
174
+ console.error('Error requesting microphone permission:', err);
175
+ allowMicrophoneElement.innerText = this.phrases.RC_microphonePermissionDenied['en-US'];
176
+ let error = JSON.stringify(err);
177
+ this.listener.sendPermissionStatus({type: 'error', error: error});
178
+ }
179
+ };
180
+
181
+ initializeSmartPhoneDisplay = () => {
182
+ const container = document.getElementById('listenerContainer');
183
+ const allowMicrophoneElement = document.getElementById('allowMicrophone');
184
+ const turnMessageElement = document.getElementById('turnMeToReadBelow');
185
+ const placeSmartphoneMicrophone = this.phrases.RC_placeSmartphoneMicrophone['en-US'];
186
+ const turnMeToReadBelow = this.phrases.RC_turnMeToReadBelow['en-US'];
187
+
188
+ allowMicrophoneElement.innerText = placeSmartphoneMicrophone;
189
+ allowMicrophoneElement.style.lineHeight = '1.2rem';
190
+ allowMicrophoneElement.style.fontSize = '14px';
191
+ turnMessageElement.innerText = turnMeToReadBelow;
192
+ turnMessageElement.style.fontSize = '14px';
193
+ turnMessageElement.style.position = 'fixed';
194
+ turnMessageElement.style.top = '20px';
195
+ turnMessageElement.style.left = '20px';
196
+ turnMessageElement.style.lineHeight = '1.2rem';
197
+ turnMessageElement.style.textAlign = 'left';
198
+
199
+ // Show the html upsidedown and adjust layout
200
+ const phrasesContainer = document.getElementById('phrases');
201
+ phrasesContainer.classList.add('phrases');
202
+
203
+ // Hide all elements except what's needed for calibration
204
+ const html = document.querySelector('html');
205
+ html.style.overflow = 'hidden';
206
+
207
+ // Adjust the display container
208
+ const display = document.getElementById('updateDisplay');
209
+ display.classList.add('updateDisplay');
210
+ display.style.position = 'absolute';
211
+ display.style.top = '70%';
212
+ display.style.left = '50%';
213
+ display.style.transform = 'translate(-50%, -50%) rotate(180deg)';
214
+ display.style.width = '100%';
215
+ display.style.textAlign = 'left';
216
+ display.style.padding = '15px';
217
+
218
+ container.style.display = 'block';
219
+
220
+ // event listener for id calibrationBeginButton
221
+ const calibrationBeginButton = document.getElementById('calibrationBeginButton');
222
+ console.log('Waiting for proceed button click');
223
+
224
+ calibrationBeginButton.addEventListener('click', async () => {
225
+ console.log('Proceed button clicked');
226
+ this.handleCalibrationButtonClick();
227
+ });
228
+ };
229
+
230
+ handleCalibrationButtonClick = async () => {
231
+ const calibrationBeginButton = document.getElementById('calibrationBeginButton');
232
+ const turnMessageElement = document.getElementById('turnMeToReadBelow');
233
+ const allowMicrophoneElement = document.getElementById('allowMicrophone');
234
+ const container = document.getElementById('listenerContainer');
235
+ const targetElement = document.getElementById('display');
236
+
237
+ // Clear unnecessary elements
238
+ calibrationBeginButton.remove();
239
+ turnMessageElement.remove();
240
+
241
+ // Create a header container for fixed elements
242
+ const headerContainer = document.createElement('div');
243
+ headerContainer.id = 'headerContainer';
244
+ headerContainer.style.position = 'fixed';
245
+ headerContainer.style.bottom = '0';
246
+ headerContainer.style.left = '0';
247
+ headerContainer.style.width = '100%';
248
+ headerContainer.style.background = 'white';
249
+ headerContainer.style.padding = '10px';
250
+ headerContainer.style.zIndex = '1000';
251
+ headerContainer.style.transform = 'rotate(180deg)';
252
+ container.appendChild(headerContainer);
253
+
254
+ // Set title based on screen width
255
+ const title = document.createElement('h1');
256
+ const titleText =
257
+ window.innerWidth >= 1366
258
+ ? this.phrases.RC_soundRecording['en-US']
259
+ : this.phrases.RC_soundRecordingSmallScreen['en-US'];
260
+
261
+ // Split small screen title into lines if needed
262
+ if (window.innerWidth < 1366 && titleText.includes('\n')) {
263
+ const lines = titleText.split('\n');
264
+
265
+ // Create container for title lines
266
+ const titleContainer = document.createElement('div');
267
+ titleContainer.style.display = 'flex';
268
+ titleContainer.style.flexDirection = 'column';
269
+ titleContainer.style.alignItems = 'left';
270
+ titleContainer.style.lineHeight = '1.2';
271
+
272
+ // Add each line
273
+ lines.forEach(line => {
274
+ const lineDiv = document.createElement('p');
275
+ lineDiv.textContent = line;
276
+ lineDiv.style.width = 'fit-content';
277
+ titleContainer.appendChild(lineDiv);
278
+ });
279
+
280
+ title.appendChild(titleContainer);
281
+ } else {
282
+ title.textContent = titleText;
283
+ title.style.lineHeight = '1.2';
284
+ }
285
+
286
+ title.style.margin = '0';
287
+ title.style.whiteSpace = 'pre-line'; // Preserve line breaks
288
+ headerContainer.appendChild(title);
289
+
290
+ // Function to adjust font size to fill width
291
+ const adjustFontSize = (element, maxWidth) => {
292
+ let fontSize = 20; // Start with a reasonable minimum size
293
+ element.style.fontSize = fontSize + 'px';
294
+ // Increase font size until text fills width (minus margins)
295
+ while (element.scrollWidth < maxWidth - 40 && fontSize < 200) {
296
+ fontSize++;
297
+ element.style.fontSize = fontSize + 'px';
298
+ }
299
+
300
+ // Step back one to ensure we don't overflow
301
+ fontSize--;
302
+ element.style.fontSize = fontSize + 'px';
303
+ return fontSize;
304
+ };
305
+
306
+ // For small screen, ensure all lines use same font size
307
+ if (window.innerWidth < 1366 && titleText.includes('\n')) {
308
+ const lines = title.querySelectorAll('p');
309
+ let minFontSize = Infinity;
310
+
311
+ // First pass: find the smallest font size that fits for any line
312
+ lines.forEach(line => {
313
+ const fontSize = adjustFontSize(line, window.innerWidth);
314
+ minFontSize = Math.min(minFontSize, fontSize);
315
+ });
316
+
317
+ // Second pass: apply the smallest font size to all lines
318
+ lines.forEach(line => {
319
+ line.style.fontSize = minFontSize + 'px';
320
+ });
321
+ } else {
322
+ // For single line title, just adjust to fill width
323
+ adjustFontSize(title, window.innerWidth);
324
+ }
325
+
326
+ // Get the header height after text is added and sized
327
+ const headerHeight = headerContainer.getBoundingClientRect().height;
328
+
329
+ // Adjust the display container to start after header
330
+ const display = document.getElementById('updateDisplay');
331
+ display.classList.add('updateDisplay');
332
+ display.style.position = 'fixed';
333
+ display.style.bottom = `${headerHeight}px`; // Start after header
334
+ display.style.left = '0';
335
+ display.style.right = '0';
336
+ display.style.top = '0';
337
+ display.style.transform = 'rotate(180deg)';
338
+ display.style.overflowY = 'auto';
339
+ display.style.padding = '20px';
340
+ display.style.background = 'white';
341
+
342
+ // Position microphone instruction at the top (appears at bottom due to rotation)
343
+ allowMicrophoneElement.innerText = '';
344
+ allowMicrophoneElement.style.position = 'fixed';
345
+ allowMicrophoneElement.style.top = '20px';
346
+ allowMicrophoneElement.style.left = '50%';
347
+ allowMicrophoneElement.style.transform = 'translateX(-50%) rotate(180deg)';
348
+ allowMicrophoneElement.style.width = '90%';
349
+ allowMicrophoneElement.style.textAlign = 'left';
350
+ allowMicrophoneElement.style.zIndex = '1000';
351
+
352
+ let lock = null;
353
+ try {
354
+ if ('wakeLock' in navigator) {
355
+ lock = await navigator.wakeLock.request('screen');
356
+ }
357
+ } catch (err) {
358
+ console.log(err);
359
+ }
360
+
361
+ this.setupMicrophone();
362
+
363
+ // show target element
364
+ targetElement.style.display = 'block';
365
+ await this.listener.startCalibration();
366
+ if (lock) {
367
+ lock.release();
368
+ }
369
+ };
370
+
371
+ setupMicrophone = async () => {
372
+ const webAudioDeviceNames = {microphone: '', deviceID: ''};
373
+ const externalMicList = ['UMIK', 'Airpods', 'Bluetooth'];
374
+ try {
375
+ const stream = await navigator.mediaDevices.getUserMedia({audio: true});
376
+ if (stream) {
377
+ const devices = await navigator.mediaDevices.enumerateDevices();
378
+ const mics = devices.filter(device => device.kind === 'audioinput');
379
+ mics.forEach(mic => {
380
+ if (externalMicList.some(externalMic => mic.label.includes(externalMic))) {
381
+ webAudioDeviceNames.microphone = mic.label;
382
+ webAudioDeviceNames.deviceID = mic.deviceId;
383
+ }
384
+ });
385
+ if (webAudioDeviceNames.microphone === '') {
386
+ webAudioDeviceNames.microphone = mics[0].label;
387
+ webAudioDeviceNames.deviceID = mics[0].deviceId;
388
+ }
389
+ }
390
+ } catch (err) {
391
+ console.log(err);
392
+ }
393
+ this.listener.setMicrophoneFromAPI(webAudioDeviceNames.microphone);
394
+ this.listener.setMicrophoneDeviceId(webAudioDeviceNames.microphone);
395
+ };
396
+
397
+ initializeDesktopMode = async () => {
398
+ await this.initializeListener();
399
+
400
+ if (await this.waitForConnection()) {
401
+ await this.setupDesktopUI();
402
+ } else {
403
+ console.error('Connection setup timed out after 30 seconds');
404
+ }
405
+ };
406
+
407
+ setupDesktopUI = async () => {
408
+ const container = document.getElementById('listenerContainer');
409
+ const recordingInProgressElement = document.getElementById('recordingInProgress');
410
+ const allowMicrophoneElement = document.getElementById('allowMicrophone');
411
+ const recordingInProgress = this.phrases.RC_soundRecording['en-US'];
412
+ const backToExperimentWindow = this.phrases.RC_backToExperimentWindow['en-US'];
413
+ const allowMicrophone = this.phrases.RC_allowMicrophoneUse['en-US'];
414
+
415
+ // remove the button
416
+ const calibrationBeginButton = document.getElementById('calibrationBeginButton');
417
+ calibrationBeginButton.remove();
418
+ container.style.display = 'block';
419
+
420
+ //update the display to be
421
+ const display = document.getElementById('display');
422
+ if (display) {
423
+ display.style.textAlign = 'left';
424
+ }
425
+
426
+ // set the text of the html elements
427
+ recordingInProgressElement.innerText = recordingInProgress;
428
+ allowMicrophoneElement.innerText = allowMicrophone;
429
+
430
+ recordingInProgressElement.style.whiteSpace = 'nowrap';
431
+ recordingInProgressElement.style.fontWeight = 'bold';
432
+
433
+ // fit content
434
+ recordingInProgressElement.style.width = 'fit-content';
435
+ let fontSize = 100;
436
+ recordingInProgressElement.style.fontSize = fontSize + 'px';
437
+
438
+ while (recordingInProgressElement.scrollWidth > window.innerWidth * 0.9 && fontSize > 10) {
439
+ fontSize--;
440
+ recordingInProgressElement.style.fontSize = fontSize + 'px';
441
+ }
442
+
443
+ const message = document.getElementById('message');
444
+ message.style.lineHeight = '2.5rem';
445
+ const p = document.createElement('p');
446
+ p.innerText = backToExperimentWindow;
447
+ message.appendChild(p);
448
+
449
+ await this.listener.startCalibration();
450
+ };
451
+ }
452
+
453
+ async function main() {
454
+ const pp = new PhonePeer();
455
+ if (window.phoneApp) {
456
+ window.phoneApp.registerSubmodule(pp);
457
+ } else {
458
+ console.log('PhoneApp not found');
459
+ }
460
+ }
461
+
462
+ main().catch(err => console.error(err));
@@ -30,9 +30,6 @@ class AudioPeer {
30
30
  * @example
31
31
  */
32
32
  constructor(param = initParameters) {
33
- this.conn = null;
34
- this.lastPeerId = null;
35
-
36
33
  // Display information to HTML elem with given id
37
34
  this.targetElement = param.targetElementId;
38
35
 
@@ -70,51 +67,6 @@ class AudioPeer {
70
67
  }
71
68
  };
72
69
 
73
- /**
74
- * Callback method for when a peer connection is lost
75
- * saves the last peer id, last server id, and attempts to reconnect.
76
- *
77
- * @example
78
- */
79
- onPeerDisconnected = () => {
80
- this.displayUpdate('Connection lost. Please reconnect');
81
-
82
- // Workaround for peer.reconnect deleting previous id
83
- try {
84
- this.peer.id = this.lastPeerId;
85
- // eslint-disable-next-line no-underscore-dangle
86
- this.peer._lastServerId = this.lastPeerId;
87
- this.peer.reconnect();
88
- } catch (e) {
89
- console.log(e);
90
- }
91
- };
92
-
93
- /** .
94
- * .
95
- * .
96
- * Callback method that cleans up after peer connection is closed
97
- *
98
- * @example
99
- */
100
- onPeerClose = () => {
101
- this.displayUpdate('Connection closed');
102
- this.conn = null;
103
- };
104
-
105
- /** .
106
- * .
107
- * .
108
- * Helper method for when an error occurs
109
- *
110
- * @param {*} err
111
- * @example
112
- */
113
- onPeerError = err => {
114
- this.displayUpdate(err);
115
- console.log(`${err}`);
116
- };
117
-
118
70
  /** .
119
71
  * .
120
72
  * .