speaker-calibration 2.2.64 → 2.2.65
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/dist/example/listener.js
CHANGED
|
@@ -125,20 +125,20 @@ try {
|
|
|
125
125
|
switch (isSmartPhone) {
|
|
126
126
|
case 'true':
|
|
127
127
|
// add turnMessageElement2 to body
|
|
128
|
-
document.body.appendChild(turnMessageElement2);
|
|
128
|
+
// document.body.appendChild(turnMessageElement2);
|
|
129
129
|
// style turnMessageElement2
|
|
130
|
-
turnMessageElement2.style.position = 'absolute';
|
|
131
|
-
turnMessageElement2.style.top = '20px';
|
|
132
|
-
turnMessageElement2.style.fontSize = 'larger';
|
|
130
|
+
// turnMessageElement2.style.position = 'absolute';
|
|
131
|
+
// turnMessageElement2.style.top = '20px';
|
|
132
|
+
// turnMessageElement2.style.fontSize = 'larger';
|
|
133
133
|
|
|
134
134
|
// add askModelNumberElement to body
|
|
135
135
|
document.body.appendChild(askModelNumberElement);
|
|
136
136
|
// style askModelNumberElement
|
|
137
|
-
askModelNumberElement.style.transform = 'rotate(180deg)';
|
|
138
|
-
askModelNumberElement.style.marginTop = '
|
|
137
|
+
// askModelNumberElement.style.transform = 'rotate(180deg)';
|
|
138
|
+
askModelNumberElement.style.marginTop = '10px';
|
|
139
139
|
askModelNumberElement.style.position = 'absolute';
|
|
140
|
-
askModelNumberElement.style.
|
|
141
|
-
askModelNumberElement.style.
|
|
140
|
+
askModelNumberElement.style.top = '0';
|
|
141
|
+
askModelNumberElement.style.left = '10px';
|
|
142
142
|
|
|
143
143
|
const askModelNumberContent = document.createElement('div');
|
|
144
144
|
askModelNumberContent.style.display = 'flex';
|
|
@@ -168,7 +168,7 @@ switch (isSmartPhone) {
|
|
|
168
168
|
// add modelNumberButton to askModelNumberContent
|
|
169
169
|
askModelNumberContent.appendChild(modelNumberButton);
|
|
170
170
|
modelNumberButton.innerHTML = 'Proceed';
|
|
171
|
-
modelNumberButton.style.width = '
|
|
171
|
+
modelNumberButton.style.width = '30%';
|
|
172
172
|
// add class
|
|
173
173
|
modelNumberButton.classList.add(...['btn', 'btn-success']);
|
|
174
174
|
modelNumberButton.addEventListener('click', async () => {
|
|
@@ -181,7 +181,8 @@ switch (isSmartPhone) {
|
|
|
181
181
|
alert('Please enter model number and name');
|
|
182
182
|
modelNumberButton.innerHTML = 'Proceed';
|
|
183
183
|
} else {
|
|
184
|
-
|
|
184
|
+
const oem = deviceInfo['OEM'].toLowerCase().split(' ').join('');
|
|
185
|
+
if (await speakerCalibrator.Speaker.doesMicrophoneExist(modelNumber, oem)) {
|
|
185
186
|
// remove the button
|
|
186
187
|
modelNumberButton.remove();
|
|
187
188
|
askModelNumberElement.remove();
|
|
@@ -232,15 +233,13 @@ switch (isSmartPhone) {
|
|
|
232
233
|
});
|
|
233
234
|
} else {
|
|
234
235
|
modelNumberButton.innerHTML = 'Proceed';
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
.replace('XXX', modelNumber);
|
|
243
|
-
}
|
|
236
|
+
p.innerHTML =
|
|
237
|
+
findModel +
|
|
238
|
+
'<br>' +
|
|
239
|
+
phrases.RC_sorryPhoneMicrophone['en-US']
|
|
240
|
+
.replace('MMM', deviceInfo['OEM'])
|
|
241
|
+
.replace('NNN', modelName)
|
|
242
|
+
.replace('xxx', modelNumber);
|
|
244
243
|
}
|
|
245
244
|
}
|
|
246
245
|
});
|
package/dist/example/styles.css
CHANGED
|
@@ -72,7 +72,7 @@ hr {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
#modelNumberInput {
|
|
75
|
-
width:
|
|
75
|
+
width: 50vw;
|
|
76
76
|
height: 100%;
|
|
77
77
|
font-size: 1rem;
|
|
78
78
|
border-radius: 5px;
|
|
@@ -82,7 +82,7 @@ hr {
|
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
#modelNameInput {
|
|
85
|
-
width:
|
|
85
|
+
width: 50vw;
|
|
86
86
|
height: 100%;
|
|
87
87
|
font-size: 1rem;
|
|
88
88
|
border-radius: 5px;
|
package/dist/main.js
CHANGED
|
@@ -774,7 +774,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var peer
|
|
|
774
774
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
775
775
|
|
|
776
776
|
"use strict";
|
|
777
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _audioPeer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./audioPeer */ \"./src/peer-connection/audioPeer.js\");\n/* harmony import */ var _peerErrors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./peerErrors */ \"./src/peer-connection/peerErrors.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n\r\n\r\n\r\n\r\n/**\r\n * @class Handles the listener's side of the connection. Responsible for getting access to user's microphone,\r\n * and initiating a call to the Speaker.\r\n * @augments AudioPeer\r\n */\r\nclass Listener extends _audioPeer__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\r\n /**\r\n * Takes a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @example\r\n */\r\n constructor(params) {\r\n super(params);\r\n\r\n this.deviceInfoFromUser = params.deviceInfoFromUser;\r\n this.startTime = Date.now();\r\n this.receiverPeerId = null;\r\n\r\n const urlParameters = this.parseURLSearchParams();\r\n this.calibrateSoundHz =\r\n urlParameters.calibrateSoundHz !== null && urlParameters.calibrateSoundHz !== undefined\r\n ? urlParameters.calibrateSoundHz\r\n : 48000;\r\n this.calibrateSoundSamplingDesiredBits =\r\n urlParameters.calibrateSoundSamplingDesiredBits !== null &&\r\n urlParameters.calibrateSoundSamplingDesiredBits !== undefined\r\n ? urlParameters.calibrateSoundSamplingDesiredBits\r\n : 24;\r\n this.speakerPeerId = urlParameters.speakerPeerId;\r\n\r\n this.peer.on('open', this.onPeerOpen);\r\n this.peer.on('connection', this.onPeerConnection);\r\n this.peer.on('disconnected', this.onPeerDisconnected);\r\n this.peer.on('close', this.onPeerClose);\r\n this.peer.on('error', this.onPeerError);\r\n }\r\n\r\n onPeerOpen = id => {\r\n this.displayUpdate('Listener - onPeerOpen');\r\n // Workaround for peer.reconnect deleting previous id\r\n\r\n if (id === null) {\r\n this.displayUpdate('Received null id from peer open');\r\n this.peer.id = this.lastPeerId;\r\n } else {\r\n this.lastPeerId = this.peer.id;\r\n }\r\n\r\n this.join();\r\n };\r\n\r\n onPeerConnection = connection => {\r\n this.displayUpdate('Listener - onPeerConnection');\r\n // Disallow incoming connections\r\n connection.on('open', () => {\r\n connection.send('Sender does not accept incoming connections');\r\n setTimeout(() => {\r\n connection.close();\r\n }, 500);\r\n });\r\n };\r\n\r\n onConnData = data => {\r\n this.displayUpdate('Listener - onConnData');\r\n const hasSpeakerID = Object.prototype.hasOwnProperty.call(data, 'speakerPeerId');\r\n if (!hasSpeakerID) {\r\n this.displayUpdate('Error in parsing data received! Must set \"speakerPeerId\" property');\r\n throw new _peerErrors__WEBPACK_IMPORTED_MODULE_1__.MissingSpeakerIdError('Must set \"speakerPeerId\" property');\r\n } else {\r\n // this.conn.close();\r\n this.displayUpdate(this.speakerPeerId);\r\n this.speakerPeerId = data.speakerPeerId;\r\n const newParams = {\r\n speakerPeerId: this.speakerPeerId,\r\n };\r\n /*\r\n FUTURE does this limit usable environments?\r\n ie does this work if internet is lost after initial page load?\r\n */\r\n window.location.search = this.queryStringFromObject(newParams); // Redirect to correctly constructed keypad page\r\n }\r\n };\r\n\r\n join = async () => {\r\n this.displayUpdate('Listener - join');\r\n /**\r\n * Create the connection between the two Peers.\r\n *\r\n * Sets up callbacks that handle any events related to the\r\n * connection and data received on it.\r\n */\r\n // Close old connection\r\n if (this.conn) {\r\n this.displayUpdate('Closing old connection');\r\n this.conn.close();\r\n }\r\n\r\n // Create connection to destination peer specified by the query param\r\n this.displayUpdate(`Creating connection to: ${this.speakerPeerId}`);\r\n this.conn = this.peer.connect(this.speakerPeerId, {\r\n reliable: true,\r\n });\r\n\r\n this.displayUpdate('Created connection');\r\n this.conn.on('open', async () => {\r\n this.displayUpdate('Listener - conn open');\r\n await this.getDeviceInfo();\r\n // this.sendSamplingRate();\r\n await this.openAudioStream();\r\n });\r\n\r\n // Handle incoming data (messages only since this is the signal sender)\r\n this.conn.on('data', this.onConnData);\r\n this.conn.on('close', () => {\r\n console.log('Connection closed');\r\n });\r\n };\r\n\r\n getMobileOS = () => {\r\n const ua = navigator.userAgent;\r\n if (/android/i.test(ua)) {\r\n return 'Android';\r\n }\r\n if (\r\n /iPad|iPhone|iPod/.test(ua) ||\r\n ((navigator?.userAgentData?.platform || navigator?.platform) === 'MacIntel' &&\r\n navigator.maxTouchPoints > 1)\r\n ) {\r\n return 'iOS';\r\n }\r\n return 'Other';\r\n };\r\n\r\n sendSamplingRate = sampleRate => {\r\n this.displayUpdate('Listener - sendSamplingRate');\r\n this.conn.send({\r\n name: 'samplingRate',\r\n payload: sampleRate,\r\n });\r\n };\r\n\r\n sendSampleSize = sampleSize => {\r\n this.displayUpdate('Listener - sendSampleSize');\r\n this.conn.send({\r\n name: 'sampleSize',\r\n payload: sampleSize,\r\n });\r\n };\r\n\r\n getDeviceInfo = async () => {\r\n try {\r\n const deviceInfo = {};\r\n fod.complete(function (data) {\r\n deviceInfo['IsMobile'] = data.device['ismobile'];\r\n deviceInfo['HardwareName'] = data.device['hardwarename'];\r\n deviceInfo['HardwareFamily'] = data.device['hardwarefamily'];\r\n deviceInfo['HardwareModel'] = data.device['hardwaremodel'];\r\n deviceInfo['OEM'] = data.device['oem'];\r\n deviceInfo['HardwareModelVariants'] = data.device['hardwaremodelvariants'];\r\n deviceInfo['DeviceId'] = data.device['deviceid'];\r\n deviceInfo['PlatformName'] = data.device['platformname'];\r\n deviceInfo['PlatformVersion'] = data.device['platformversion'];\r\n deviceInfo['DeviceType'] = data.device['devicetype'];\r\n deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\r\n });\r\n this.conn.send({\r\n name: 'deviceInfo',\r\n payload: deviceInfo,\r\n });\r\n return deviceInfo;\r\n } catch (error) {\r\n console.error('Error fetching or executing script:', error.message);\r\n return null;\r\n }\r\n };\r\n\r\n applyHQTrackConstraints = async stream => {\r\n // Contraint the incoming audio to the sampling rate we want\r\n\r\n const track = stream.getAudioTracks()[0];\r\n const capabilities = track.getCapabilities();\r\n\r\n this.displayUpdate(\r\n `Listener Track Capabilities - ${JSON.stringify(capabilities, undefined, 2)}`\r\n );\r\n\r\n const constraints = track.getConstraints();\r\n\r\n if (capabilities.echoCancellation) {\r\n constraints.echoCancellation = false;\r\n }\r\n\r\n if (capabilities.sampleRate) {\r\n constraints.sampleRate = this.calibrateSoundHz;\r\n }\r\n\r\n if (capabilities.sampleSize) {\r\n constraints.sampleSize = this.calibrateSoundSamplingDesiredBits;\r\n }\r\n\r\n if (capabilities.channelCount) {\r\n constraints.channelCount = 1;\r\n }\r\n\r\n this.displayUpdate(`Listener Track Constraints - ${JSON.stringify(constraints, undefined, 2)}`);\r\n\r\n // await the promise\r\n try {\r\n await track.applyConstraints(constraints);\r\n } catch (err) {\r\n console.error(err);\r\n this.displayUpdate(`Error applying constraints to track: ${err}`);\r\n }\r\n\r\n const settings = track.getSettings();\r\n this.displayUpdate(`Listener Track Settings - ${JSON.stringify(settings, undefined, 2)}`);\r\n return settings;\r\n };\r\n\r\n getMediaDevicesAudioContraints = () => {\r\n const availableConstraints = navigator.mediaDevices.getSupportedConstraints();\r\n\r\n this.displayUpdate(\r\n `Listener MediaDevices Available Contraints - ${JSON.stringify(\r\n availableConstraints,\r\n undefined,\r\n 2\r\n )}`\r\n );\r\n\r\n const contraints = {\r\n // ...(availableConstraints.echoCancellation && availableConstraints.echoCancellation == true\r\n // ? {echoCancellation: {exact: false}}\r\n // : {}),\r\n ...(availableConstraints.sampleRate && availableConstraints.sampleRate == true\r\n ? {sampleRate: {ideal: this.calibrateSoundHz}}\r\n : {}),\r\n ...(availableConstraints.sampleSize && availableConstraints.sampleSize == true\r\n ? {sampleSize: {ideal: this.calibrateSoundSamplingDesiredBits}}\r\n : {}),\r\n ...(availableConstraints.channelCount && availableConstraints.channelCount == true\r\n ? {channelCount: {exact: 1}}\r\n : {}),\r\n echoCancellation: false,\r\n noiseSuppression: false,\r\n autoGainControl: false,\r\n };\r\n\r\n console.log(contraints);\r\n\r\n this.displayUpdate(\r\n `Listener MediaDevices Contraints - ${JSON.stringify(contraints, undefined, 2)}`\r\n );\r\n\r\n return contraints;\r\n };\r\n\r\n openAudioStream = async () => {\r\n this.displayUpdate('Listener - openAudioStream');\r\n const mobileOS = this.getMobileOS();\r\n if (false) {}\r\n\r\n navigator.mediaDevices\r\n .getUserMedia({\r\n audio: this.getMediaDevicesAudioContraints(),\r\n video: false,\r\n })\r\n .then(stream => {\r\n this.applyHQTrackConstraints(stream)\r\n .then(settings => {\r\n this.sendSamplingRate(settings.sampleRate);\r\n this.sendSampleSize(settings.sampleSize);\r\n this.peer.call(this.speakerPeerId, stream); // one-way call\r\n this.displayUpdate('Listener - openAudioStream');\r\n })\r\n .catch(err => {\r\n console.log(err);\r\n this.displayUpdate(\r\n `Listener - Error in applyHQTrackConstraints - ${JSON.stringify(err, undefined, 2)}`\r\n );\r\n });\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n this.displayUpdate(\r\n `Listener - Error in getUserMedia - ${JSON.stringify(err, undefined, 2)}`\r\n );\r\n });\r\n };\r\n}\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Listener);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/listener.js?");
|
|
777
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _audioPeer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./audioPeer */ \"./src/peer-connection/audioPeer.js\");\n/* harmony import */ var _peerErrors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./peerErrors */ \"./src/peer-connection/peerErrors.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n\r\n\r\n\r\n\r\n/**\r\n * @class Handles the listener's side of the connection. Responsible for getting access to user's microphone,\r\n * and initiating a call to the Speaker.\r\n * @augments AudioPeer\r\n */\r\nclass Listener extends _audioPeer__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\r\n /**\r\n * Takes a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @example\r\n */\r\n constructor(params) {\r\n super(params);\r\n this.deviceInfoFromUser = params.deviceInfoFromUser\r\n ? params.deviceInfoFromUser\r\n : {modelNumber: '', modelName: ''};\r\n this.startTime = Date.now();\r\n this.receiverPeerId = null;\r\n\r\n const urlParameters = this.parseURLSearchParams();\r\n this.calibrateSoundHz =\r\n urlParameters.calibrateSoundHz !== null && urlParameters.calibrateSoundHz !== undefined\r\n ? urlParameters.calibrateSoundHz\r\n : 48000;\r\n this.calibrateSoundSamplingDesiredBits =\r\n urlParameters.calibrateSoundSamplingDesiredBits !== null &&\r\n urlParameters.calibrateSoundSamplingDesiredBits !== undefined\r\n ? urlParameters.calibrateSoundSamplingDesiredBits\r\n : 24;\r\n this.speakerPeerId = urlParameters.speakerPeerId;\r\n\r\n this.peer.on('open', this.onPeerOpen);\r\n this.peer.on('connection', this.onPeerConnection);\r\n this.peer.on('disconnected', this.onPeerDisconnected);\r\n this.peer.on('close', this.onPeerClose);\r\n this.peer.on('error', this.onPeerError);\r\n }\r\n\r\n onPeerOpen = id => {\r\n this.displayUpdate('Listener - onPeerOpen');\r\n // Workaround for peer.reconnect deleting previous id\r\n\r\n if (id === null) {\r\n this.displayUpdate('Received null id from peer open');\r\n this.peer.id = this.lastPeerId;\r\n } else {\r\n this.lastPeerId = this.peer.id;\r\n }\r\n\r\n this.join();\r\n };\r\n\r\n onPeerConnection = connection => {\r\n this.displayUpdate('Listener - onPeerConnection');\r\n // Disallow incoming connections\r\n connection.on('open', () => {\r\n connection.send('Sender does not accept incoming connections');\r\n setTimeout(() => {\r\n connection.close();\r\n }, 500);\r\n });\r\n };\r\n\r\n onConnData = data => {\r\n this.displayUpdate('Listener - onConnData');\r\n const hasSpeakerID = Object.prototype.hasOwnProperty.call(data, 'speakerPeerId');\r\n if (!hasSpeakerID) {\r\n this.displayUpdate('Error in parsing data received! Must set \"speakerPeerId\" property');\r\n throw new _peerErrors__WEBPACK_IMPORTED_MODULE_1__.MissingSpeakerIdError('Must set \"speakerPeerId\" property');\r\n } else {\r\n // this.conn.close();\r\n this.displayUpdate(this.speakerPeerId);\r\n this.speakerPeerId = data.speakerPeerId;\r\n const newParams = {\r\n speakerPeerId: this.speakerPeerId,\r\n };\r\n /*\r\n FUTURE does this limit usable environments?\r\n ie does this work if internet is lost after initial page load?\r\n */\r\n window.location.search = this.queryStringFromObject(newParams); // Redirect to correctly constructed keypad page\r\n }\r\n };\r\n\r\n join = async () => {\r\n this.displayUpdate('Listener - join');\r\n /**\r\n * Create the connection between the two Peers.\r\n *\r\n * Sets up callbacks that handle any events related to the\r\n * connection and data received on it.\r\n */\r\n // Close old connection\r\n if (this.conn) {\r\n this.displayUpdate('Closing old connection');\r\n this.conn.close();\r\n }\r\n\r\n // Create connection to destination peer specified by the query param\r\n this.displayUpdate(`Creating connection to: ${this.speakerPeerId}`);\r\n this.conn = this.peer.connect(this.speakerPeerId, {\r\n reliable: true,\r\n });\r\n\r\n this.displayUpdate('Created connection');\r\n this.conn.on('open', async () => {\r\n this.displayUpdate('Listener - conn open');\r\n await this.getDeviceInfo();\r\n // this.sendSamplingRate();\r\n await this.openAudioStream();\r\n });\r\n\r\n // Handle incoming data (messages only since this is the signal sender)\r\n this.conn.on('data', this.onConnData);\r\n this.conn.on('close', () => {\r\n console.log('Connection closed');\r\n });\r\n };\r\n\r\n getMobileOS = () => {\r\n const ua = navigator.userAgent;\r\n if (/android/i.test(ua)) {\r\n return 'Android';\r\n }\r\n if (\r\n /iPad|iPhone|iPod/.test(ua) ||\r\n ((navigator?.userAgentData?.platform || navigator?.platform) === 'MacIntel' &&\r\n navigator.maxTouchPoints > 1)\r\n ) {\r\n return 'iOS';\r\n }\r\n return 'Other';\r\n };\r\n\r\n sendSamplingRate = sampleRate => {\r\n this.displayUpdate('Listener - sendSamplingRate');\r\n this.conn.send({\r\n name: 'samplingRate',\r\n payload: sampleRate,\r\n });\r\n };\r\n\r\n sendSampleSize = sampleSize => {\r\n this.displayUpdate('Listener - sendSampleSize');\r\n this.conn.send({\r\n name: 'sampleSize',\r\n payload: sampleSize,\r\n });\r\n };\r\n\r\n getDeviceInfo = async () => {\r\n try {\r\n const deviceInfo = {};\r\n fod.complete(function (data) {\r\n deviceInfo['IsMobile'] = data.device['ismobile'];\r\n deviceInfo['HardwareName'] = data.device['hardwarename'];\r\n deviceInfo['HardwareFamily'] = data.device['hardwarefamily'];\r\n deviceInfo['HardwareModel'] = data.device['hardwaremodel'];\r\n deviceInfo['OEM'] = data.device['oem'];\r\n deviceInfo['HardwareModelVariants'] = data.device['hardwaremodelvariants'];\r\n deviceInfo['DeviceId'] = data.device['deviceid'];\r\n deviceInfo['PlatformName'] = data.device['platformname'];\r\n deviceInfo['PlatformVersion'] = data.device['platformversion'];\r\n deviceInfo['DeviceType'] = data.device['devicetype'];\r\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\r\n });\r\n deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\r\n this.conn.send({\r\n name: 'deviceInfo',\r\n payload: deviceInfo,\r\n });\r\n return deviceInfo;\r\n } catch (error) {\r\n console.error('Error fetching or executing script:', error.message);\r\n return null;\r\n }\r\n };\r\n\r\n applyHQTrackConstraints = async stream => {\r\n // Contraint the incoming audio to the sampling rate we want\r\n\r\n const track = stream.getAudioTracks()[0];\r\n const capabilities = track.getCapabilities();\r\n\r\n this.displayUpdate(\r\n `Listener Track Capabilities - ${JSON.stringify(capabilities, undefined, 2)}`\r\n );\r\n\r\n const constraints = track.getConstraints();\r\n\r\n if (capabilities.echoCancellation) {\r\n constraints.echoCancellation = false;\r\n }\r\n\r\n if (capabilities.sampleRate) {\r\n constraints.sampleRate = this.calibrateSoundHz;\r\n }\r\n\r\n if (capabilities.sampleSize) {\r\n constraints.sampleSize = this.calibrateSoundSamplingDesiredBits;\r\n }\r\n\r\n if (capabilities.channelCount) {\r\n constraints.channelCount = 1;\r\n }\r\n\r\n this.displayUpdate(`Listener Track Constraints - ${JSON.stringify(constraints, undefined, 2)}`);\r\n\r\n // await the promise\r\n try {\r\n await track.applyConstraints(constraints);\r\n } catch (err) {\r\n console.error(err);\r\n this.displayUpdate(`Error applying constraints to track: ${err}`);\r\n }\r\n\r\n const settings = track.getSettings();\r\n this.displayUpdate(`Listener Track Settings - ${JSON.stringify(settings, undefined, 2)}`);\r\n return settings;\r\n };\r\n\r\n getMediaDevicesAudioContraints = () => {\r\n const availableConstraints = navigator.mediaDevices.getSupportedConstraints();\r\n\r\n this.displayUpdate(\r\n `Listener MediaDevices Available Contraints - ${JSON.stringify(\r\n availableConstraints,\r\n undefined,\r\n 2\r\n )}`\r\n );\r\n\r\n const contraints = {\r\n // ...(availableConstraints.echoCancellation && availableConstraints.echoCancellation == true\r\n // ? {echoCancellation: {exact: false}}\r\n // : {}),\r\n ...(availableConstraints.sampleRate && availableConstraints.sampleRate == true\r\n ? {sampleRate: {ideal: this.calibrateSoundHz}}\r\n : {}),\r\n ...(availableConstraints.sampleSize && availableConstraints.sampleSize == true\r\n ? {sampleSize: {ideal: this.calibrateSoundSamplingDesiredBits}}\r\n : {}),\r\n ...(availableConstraints.channelCount && availableConstraints.channelCount == true\r\n ? {channelCount: {exact: 1}}\r\n : {}),\r\n echoCancellation: false,\r\n noiseSuppression: false,\r\n autoGainControl: false,\r\n };\r\n\r\n console.log(contraints);\r\n\r\n this.displayUpdate(\r\n `Listener MediaDevices Contraints - ${JSON.stringify(contraints, undefined, 2)}`\r\n );\r\n\r\n return contraints;\r\n };\r\n\r\n openAudioStream = async () => {\r\n this.displayUpdate('Listener - openAudioStream');\r\n const mobileOS = this.getMobileOS();\r\n if (false) {}\r\n\r\n navigator.mediaDevices\r\n .getUserMedia({\r\n audio: this.getMediaDevicesAudioContraints(),\r\n video: false,\r\n })\r\n .then(stream => {\r\n this.applyHQTrackConstraints(stream)\r\n .then(settings => {\r\n this.sendSamplingRate(settings.sampleRate);\r\n this.sendSampleSize(settings.sampleSize);\r\n this.peer.call(this.speakerPeerId, stream); // one-way call\r\n this.displayUpdate('Listener - openAudioStream');\r\n })\r\n .catch(err => {\r\n console.log(err);\r\n this.displayUpdate(\r\n `Listener - Error in applyHQTrackConstraints - ${JSON.stringify(err, undefined, 2)}`\r\n );\r\n });\r\n })\r\n .catch(err => {\r\n console.error(err);\r\n this.displayUpdate(\r\n `Listener - Error in getUserMedia - ${JSON.stringify(err, undefined, 2)}`\r\n );\r\n });\r\n };\r\n}\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Listener);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/listener.js?");
|
|
778
778
|
|
|
779
779
|
/***/ }),
|
|
780
780
|
|
|
@@ -796,7 +796,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
|
|
|
796
796
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
797
797
|
|
|
798
798
|
"use strict";
|
|
799
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var qrcode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! qrcode */ \"./node_modules/qrcode/lib/browser.js\");\n/* harmony import */ var _audioPeer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./audioPeer */ \"./src/peer-connection/audioPeer.js\");\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ \"./src/utils.js\");\n/* harmony import */ var _peerErrors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./peerErrors */ \"./src/peer-connection/peerErrors.js\");\n/* harmony import */ var _config_firebase__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../config/firebase */ \"./src/config/firebase.js\");\n/* harmony import */ var firebase_database__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! firebase/database */ \"./node_modules/firebase/database/dist/esm/index.esm.js\");\n/* harmony import */ var _dist_example_i18n__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../dist/example/i18n */ \"./dist/example/i18n.js\");\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n/**\r\n * @class Handles the speaker's side of the connection. Responsible for initiating the connection,\r\n * rendering the QRCode, and answering the call.\r\n * @augments AudioPeer\r\n */\r\nclass Speaker extends _audioPeer__WEBPACK_IMPORTED_MODULE_1__[\"default\"] {\r\n /**\r\n * Takes the url of the current site and a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.\r\n * @param CalibratorInstance\r\n * @example\r\n */\r\n constructor(params, CalibratorInstance) {\r\n super(params);\r\n this.siteUrl += '/listener?';\r\n this.ac = CalibratorInstance;\r\n this.result = null;\r\n this.debug = params?.debug ?? false;\r\n this.isSmartPhone = params?.isSmartPhone ?? false;\r\n this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;\r\n this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;\r\n this.instructionDisplayId = params?.instructionDisplayId ?? '';\r\n this.timeToCalibrateDisplay = params?.timeToCalibrateId ?? '';\r\n this.soundMessageId = params?.soundMessageId ?? '';\r\n this.titleDisplayId = params?.titleDisplayId ?? '';\r\n this.timeToCalibrate = params?.timeToCalibrate ?? 10;\r\n\r\n /* Set up callbacks that handle any events related to our peer object. */\r\n this.peer.on('open', this.#onPeerOpen);\r\n this.peer.on('connection', this.#onPeerConnection);\r\n this.peer.on('close', this.#onPeerClose);\r\n this.peer.on('disconnected', this.#onPeerDisconnected);\r\n this.peer.on('error', this.#onPeerError);\r\n }\r\n\r\n static getMicrophoneNamesFromDatabase = async () => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_4__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.child)(dbRef, 'Microphone'));\r\n if (snapshot.exists()) {\r\n return Object.keys(snapshot.val());\r\n }\r\n return null;\r\n };\r\n\r\n static doesMicrophoneExist = async (speakerID, OEM) => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_4__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.child)(dbRef, `Microphone2/${OEM}/${speakerID}`));\r\n if (snapshot.exists()) {\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n /**\r\n * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.\r\n *\r\n * @param params - The parameters to be passed to the peer object.\r\n * @param Calibrator - The class that defines the calibration process.\r\n * @param CalibratorInstance\r\n * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).\r\n * @public\r\n * @example\r\n */\r\n static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {\r\n window.speaker = new Speaker(params, CalibratorInstance);\r\n const {speaker} = window;\r\n\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise((resolve, reject) => {\r\n // when a call is received\r\n speaker.peer.on('call', async call => {\r\n // Answer the call (one way)\r\n\r\n call.answer();\r\n speaker.#removeUIElems();\r\n speaker.#showSpinner();\r\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\r\n // when we start receiving audio\r\n call.on('stream', async stream => {\r\n window.localStream = stream;\r\n window.localAudio.srcObject = stream;\r\n window.localAudio.autoplay = false;\r\n\r\n // if the sinkSamplingRate is not set sleep\r\n while (!speaker.ac.sampleRatesSet()) {\r\n console.log('SinkSamplingRate is undefined, sleeping');\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\r\n }\r\n // resolve when we have a result\r\n speaker.result = await speaker.ac.startCalibration(\r\n stream,\r\n params.gainValues,\r\n params.ICalib,\r\n params.knownIR,\r\n params.microphoneName,\r\n params.calibrateSoundCheck,\r\n params.isSmartPhone,\r\n params.calibrateSoundBurstDb,\r\n params.calibrateSoundBurstRepeats,\r\n params.calibrateSoundBurstSec,\r\n params.calibrateSoundBurstsWarmup,\r\n params.calibrateSoundHz,\r\n params.calibrateSoundIIRSec,\r\n params.calibrateSound1000HzPreSec,\r\n params.calibrateSound1000HzSec,\r\n params.calibrateSound1000HzPostSec,\r\n params.calibrateSoundBackgroundSecs,\r\n params.micManufacturer,\r\n params.micSerialNumber,\r\n params.micModelNumber,\r\n params.micModelName\r\n );\r\n speaker.#removeUIElems();\r\n resolve(speaker.result);\r\n });\r\n // if we do not receive a result within the timeout, reject\r\n setTimeout(() => {\r\n reject(\r\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\r\n `Calibration failed to produce a result after ${\r\n timeOut / 1000\r\n } seconds. Please try again.`\r\n )\r\n );\r\n }, timeOut);\r\n });\r\n });\r\n };\r\n\r\n static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {\r\n window.speaker = new Speaker(params, CalibratorInstance);\r\n const {speaker} = window;\r\n\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise((resolve, reject) => {\r\n // when a call is received\r\n speaker.peer.on('call', async call => {\r\n // Answer the call (one way)\r\n call.answer();\r\n speaker.#removeUIElems();\r\n speaker.#showSpinner();\r\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\r\n // when we start receiving audio\r\n call.on('stream', async stream => {\r\n window.localStream = stream;\r\n window.localAudio.srcObject = stream;\r\n window.localAudio.autoplay = false;\r\n\r\n // if the sinkSamplingRate is not set sleep\r\n while (!speaker.ac.sampleRatesSet()) {\r\n console.log('SinkSamplingRate is undefined, sleeping');\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\r\n }\r\n // resolve when we have a result\r\n speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);\r\n speaker.#removeUIElems();\r\n resolve(speaker.result);\r\n });\r\n // if we do not receive a result within the timeout, reject\r\n setTimeout(() => {\r\n reject(\r\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\r\n `Calibration failed to produce a result after ${\r\n timeOut / 1000\r\n } seconds. Please try again.`\r\n )\r\n );\r\n }, timeOut);\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Called after the peer conncection has been opened.\r\n * Generates a QR code for the connection and displays it.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #showQRCode = () => {\r\n // Get query string, the URL parameters to specify a Listener\r\n const queryStringParameters = {\r\n speakerPeerId: this.peer.id,\r\n isSmartPhone: this.isSmartPhone,\r\n calibrateSoundHz: this.calibrateSoundHz,\r\n calibrateSoundSamplingDesiredBits: this.calibrateSoundSamplingDesiredBits,\r\n };\r\n const queryString = this.queryStringFromObject(queryStringParameters);\r\n const uri = this.siteUrl + queryString;\r\n if (this.isSmartPhone) {\r\n // Display QR code for the participant to scan\r\n const qrCanvas = document.createElement('canvas');\r\n qrCanvas.setAttribute('id', 'qrCanvas');\r\n console.log(uri);\r\n qrcode__WEBPACK_IMPORTED_MODULE_0__.toCanvas(qrCanvas, uri, error => {\r\n if (error) console.error(error);\r\n });\r\n document.getElementById(this.targetElement).appendChild(qrCanvas);\r\n } else {\r\n // show the link to the user\r\n // If specified HTML Id is available, show QR code there\r\n if (document.getElementById(this.targetElement)) {\r\n // const linkTag = document.createElement('a');\r\n // linkTag.setAttribute('href', uri);\r\n // linkTag.innerHTML = 'Click here to start the calibration';\r\n // linkTag.target = '_blank';\r\n // document.getElementById(this.targetElement).appendChild(linkTag);\r\n // document.getElementById(this.targetElement).appendChild(qrCanvas);\r\n\r\n const proceedButton = document.createElement('button');\r\n proceedButton.setAttribute('id', 'calibrationProceedButton');\r\n proceedButton.setAttribute('class', 'btn btn-success');\r\n proceedButton.innerHTML = 'Proceed';\r\n proceedButton.onclick = () => {\r\n // open the link in a new tab\r\n window.open(uri, '_blank');\r\n // remove the button\r\n document.getElementById('calibrationProceedButton').remove();\r\n };\r\n document.getElementById(this.targetElement).appendChild(proceedButton);\r\n }\r\n }\r\n // or just print it to console\r\n console.log('TEST: Peer reachable at: ', uri);\r\n };\r\n\r\n #showSpinner = () => {\r\n const spinner = document.createElement('div');\r\n spinner.className = 'spinner-border ml-auto';\r\n spinner.role = 'status';\r\n spinner.ariaHidden = 'true';\r\n document.getElementById(this.targetElement).appendChild(spinner);\r\n\r\n // clear instructionDisplay\r\n const soundMessage = document.getElementById(this.soundMessageId);\r\n soundMessage.innerHTML = '';\r\n soundMessage.style.display = 'none';\r\n const instructionDisplay = document.getElementById(this.instructionDisplayId);\r\n const background = document.getElementById('background'); // todo: get background id from params\r\n if (instructionDisplay) {\r\n instructionDisplay.innerHTML = '';\r\n instructionDisplay.style.whiteSpace = 'nowrap';\r\n instructionDisplay.style.fontWeight = 'bold';\r\n instructionDisplay.style.width = 'fit-content';\r\n instructionDisplay.innerHTML = _dist_example_i18n__WEBPACK_IMPORTED_MODULE_6__.phrases.RC_soundRecording[\"en-US\"];\r\n let fontSize = 100;\r\n instructionDisplay.style.fontSize = fontSize + 'px';\r\n while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {\r\n fontSize--;\r\n instructionDisplay.style.fontSize = fontSize + 'px';\r\n }\r\n // const p = document.createElement('p');\r\n // // font size\r\n // p.style.fontSize = '1.1rem';\r\n // p.style.fontWeight = 'normal';\r\n // p.style.paddingTop = '20px';\r\n // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];\r\n // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\r\n // instructionDisplay.appendChild(p);\r\n }\r\n\r\n const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);\r\n if (timeToCalibrateDisplay) {\r\n const timeToCalibrateText = _dist_example_i18n__WEBPACK_IMPORTED_MODULE_6__.phrases.RC_howLongToCalibrate[\"en-US\"];\r\n timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\r\n timeToCalibrateDisplay.style.fontWeight = 'normal';\r\n timeToCalibrateDisplay.style.fontSize = '1rem';\r\n // timeToCalibrateDisplay.style.paddingTop = '20px';\r\n }\r\n\r\n // Update title - titleDisplayId\r\n const titleDisplay = document.getElementById(this.titleDisplayId);\r\n if (titleDisplay) {\r\n // replace 5 with 6\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');\r\n }\r\n };\r\n\r\n #removeUIElems = () => {\r\n const parent = document.getElementById(this.targetElement);\r\n while (parent.firstChild) {\r\n parent.firstChild.remove();\r\n }\r\n };\r\n\r\n /**\r\n * Called when the peer connection is opened.\r\n * Saves the peer id and calls the QR code generator.\r\n *\r\n * @param peerId - The peer id of the peer connection.\r\n * @param id\r\n * @private\r\n * @example\r\n */\r\n #onPeerOpen = id => {\r\n // Workaround for peer.reconnect deleting previous id\r\n if (id === null) {\r\n console.error('Received null id from peer open');\r\n this.peer.id = this.lastPeerId;\r\n } else {\r\n this.lastPeerId = this.peer.id;\r\n }\r\n\r\n if (id !== this.peer.id) {\r\n console.warn('DEBUG Check you assumption that id === this.peer.id');\r\n }\r\n\r\n this.#showQRCode();\r\n };\r\n\r\n /**\r\n * Called when the peer connection is established.\r\n * Enforces a single connection.\r\n *\r\n * @param connection - The connection object.\r\n * @private\r\n * @example\r\n */\r\n #onPeerConnection = connection => {\r\n // Allow only a single connection\r\n if (this.conn && this.conn.open) {\r\n connection.on('open', () => {\r\n connection.send('Already connected to another client');\r\n setTimeout(() => {\r\n connection.close();\r\n }, 500);\r\n });\r\n return;\r\n }\r\n\r\n this.conn = connection;\r\n console.log('Connected to: ', this.conn.peer);\r\n this.#ready();\r\n };\r\n\r\n /**\r\n * Called when the peer connection is closed.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #onPeerClose = () => {\r\n this.conn = null;\r\n console.log('Connection destroyed');\r\n };\r\n\r\n /**\r\n * Called when the peer connection is disconnected.\r\n * Attempts to reconnect.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #onPeerDisconnected = () => {\r\n console.log('Connection lost. Please reconnect');\r\n\r\n // Workaround for peer.reconnect deleting previous id\r\n this.peer.id = this.lastPeerId;\r\n // eslint-disable-next-line no-underscore-dangle\r\n this.peer._lastServerId = this.lastPeerId;\r\n this.peer.reconnect();\r\n };\r\n\r\n /**\r\n * Called when the peer connection encounters an error.\r\n *\r\n * @param error\r\n * @private\r\n * @example\r\n */\r\n #onPeerError = error => {\r\n // TODO: check if this function is needed or not\r\n console.error(error);\r\n };\r\n\r\n /**\r\n * Called when data is received from the peer connection.\r\n *\r\n * @param data\r\n * @private\r\n * @example\r\n */\r\n #onIncomingData = data => {\r\n // enforce object type\r\n if (\r\n !Object.prototype.hasOwnProperty.call(data, 'name') ||\r\n !Object.prototype.hasOwnProperty.call(data, 'payload')\r\n ) {\r\n console.error('Received malformed data: ', data);\r\n return;\r\n }\r\n\r\n switch (data.name) {\r\n case 'samplingRate':\r\n this.ac.setSamplingRates(data.payload);\r\n break;\r\n case 'sampleSize':\r\n this.ac.setSampleSize(data.payload);\r\n break;\r\n case 'deviceType':\r\n this.ac.setDeviceType(data.payload);\r\n break;\r\n case 'deviceName':\r\n this.ac.setDeviceName(data.payload);\r\n break;\r\n case 'deviceInfo':\r\n this.ac.setDeviceInfo(data.payload);\r\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.UnsupportedDeviceError.name:\r\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.MissingSpeakerIdError.name:\r\n throw data.payload;\r\n break;\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Called when the peer connection is #ready.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #ready = () => {\r\n // Perform callback with data\r\n this.conn.on('data', this.#onIncomingData);\r\n this.conn.on('close', () => {\r\n console.log('Connection reset<br>Awaiting connection...');\r\n this.conn = null;\r\n });\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Debug method for downloading the recorded audio\r\n *\r\n * @public\r\n * @example\r\n */\r\n downloadData = () => {\r\n this.ac.downloadData();\r\n };\r\n}\r\n\r\n/* \r\nReferenced links:\r\nhttps://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676\r\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\r\nhttps://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]\r\n*/\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Speaker);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/speaker.js?");
|
|
799
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var qrcode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! qrcode */ \"./node_modules/qrcode/lib/browser.js\");\n/* harmony import */ var _audioPeer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./audioPeer */ \"./src/peer-connection/audioPeer.js\");\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ \"./src/utils.js\");\n/* harmony import */ var _peerErrors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./peerErrors */ \"./src/peer-connection/peerErrors.js\");\n/* harmony import */ var _config_firebase__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../config/firebase */ \"./src/config/firebase.js\");\n/* harmony import */ var firebase_database__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! firebase/database */ \"./node_modules/firebase/database/dist/esm/index.esm.js\");\n/* harmony import */ var _dist_example_i18n__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../dist/example/i18n */ \"./dist/example/i18n.js\");\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n/**\r\n * @class Handles the speaker's side of the connection. Responsible for initiating the connection,\r\n * rendering the QRCode, and answering the call.\r\n * @augments AudioPeer\r\n */\r\nclass Speaker extends _audioPeer__WEBPACK_IMPORTED_MODULE_1__[\"default\"] {\r\n /**\r\n * Takes the url of the current site and a target element where html elements will be appended.\r\n *\r\n * @param params - See type definition for initParameters.\r\n * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.\r\n * @param CalibratorInstance\r\n * @example\r\n */\r\n constructor(params, CalibratorInstance) {\r\n super(params);\r\n this.siteUrl += '/listener?';\r\n this.ac = CalibratorInstance;\r\n this.result = null;\r\n this.debug = params?.debug ?? false;\r\n this.isSmartPhone = params?.isSmartPhone ?? false;\r\n this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;\r\n this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;\r\n this.instructionDisplayId = params?.instructionDisplayId ?? '';\r\n this.timeToCalibrateDisplay = params?.timeToCalibrateId ?? '';\r\n this.soundMessageId = params?.soundMessageId ?? '';\r\n this.titleDisplayId = params?.titleDisplayId ?? '';\r\n this.timeToCalibrate = params?.timeToCalibrate ?? 10;\r\n\r\n /* Set up callbacks that handle any events related to our peer object. */\r\n this.peer.on('open', this.#onPeerOpen);\r\n this.peer.on('connection', this.#onPeerConnection);\r\n this.peer.on('close', this.#onPeerClose);\r\n this.peer.on('disconnected', this.#onPeerDisconnected);\r\n this.peer.on('error', this.#onPeerError);\r\n }\r\n\r\n static getMicrophoneNamesFromDatabase = async () => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_4__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.child)(dbRef, 'Microphone'));\r\n if (snapshot.exists()) {\r\n return Object.keys(snapshot.val());\r\n }\r\n return null;\r\n };\r\n\r\n static doesMicrophoneExist = async (speakerID, OEM) => {\r\n const dbRef = (0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.ref)(_config_firebase__WEBPACK_IMPORTED_MODULE_4__[\"default\"]);\r\n const snapshot = await (0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.get)((0,firebase_database__WEBPACK_IMPORTED_MODULE_5__.child)(dbRef, `Microphone2/${OEM}/${speakerID}`));\r\n if (snapshot.exists()) {\r\n return true;\r\n }\r\n return false;\r\n };\r\n\r\n /**\r\n * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.\r\n *\r\n * @param params - The parameters to be passed to the peer object.\r\n * @param Calibrator - The class that defines the calibration process.\r\n * @param CalibratorInstance\r\n * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).\r\n * @public\r\n * @example\r\n */\r\n static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {\r\n window.speaker = new Speaker(params, CalibratorInstance);\r\n const {speaker} = window;\r\n\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise((resolve, reject) => {\r\n // when a call is received\r\n speaker.peer.on('call', async call => {\r\n // Answer the call (one way)\r\n\r\n call.answer();\r\n speaker.#removeUIElems();\r\n speaker.#showSpinner();\r\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\r\n // when we start receiving audio\r\n call.on('stream', async stream => {\r\n window.localStream = stream;\r\n window.localAudio.srcObject = stream;\r\n window.localAudio.autoplay = false;\r\n\r\n // if the sinkSamplingRate is not set sleep\r\n while (!speaker.ac.sampleRatesSet()) {\r\n console.log('SinkSamplingRate is undefined, sleeping');\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\r\n }\r\n // resolve when we have a result\r\n speaker.result = await speaker.ac.startCalibration(\r\n stream,\r\n params.gainValues,\r\n params.ICalib,\r\n params.knownIR,\r\n params.microphoneName,\r\n params.calibrateSoundCheck,\r\n params.isSmartPhone,\r\n params.calibrateSoundBurstDb,\r\n params.calibrateSoundBurstRepeats,\r\n params.calibrateSoundBurstSec,\r\n params.calibrateSoundBurstsWarmup,\r\n params.calibrateSoundHz,\r\n params.calibrateSoundIIRSec,\r\n params.calibrateSound1000HzPreSec,\r\n params.calibrateSound1000HzSec,\r\n params.calibrateSound1000HzPostSec,\r\n params.calibrateSoundBackgroundSecs,\r\n params.micManufacturer,\r\n params.micSerialNumber,\r\n params.micModelNumber,\r\n params.micModelName\r\n );\r\n speaker.#removeUIElems();\r\n resolve(speaker.result);\r\n });\r\n // if we do not receive a result within the timeout, reject\r\n setTimeout(() => {\r\n reject(\r\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\r\n `Calibration failed to produce a result after ${\r\n timeOut / 1000\r\n } seconds. Please try again.`\r\n )\r\n );\r\n }, timeOut);\r\n });\r\n });\r\n };\r\n\r\n static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {\r\n window.speaker = new Speaker(params, CalibratorInstance);\r\n const {speaker} = window;\r\n\r\n // wrap the calibration process in a promise so we can await it\r\n return new Promise((resolve, reject) => {\r\n // when a call is received\r\n speaker.peer.on('call', async call => {\r\n // Answer the call (one way)\r\n call.answer();\r\n speaker.#removeUIElems();\r\n speaker.#showSpinner();\r\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\r\n // when we start receiving audio\r\n call.on('stream', async stream => {\r\n window.localStream = stream;\r\n window.localAudio.srcObject = stream;\r\n window.localAudio.autoplay = false;\r\n\r\n // if the sinkSamplingRate is not set sleep\r\n while (!speaker.ac.sampleRatesSet()) {\r\n console.log('SinkSamplingRate is undefined, sleeping');\r\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\r\n }\r\n // resolve when we have a result\r\n speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);\r\n speaker.#removeUIElems();\r\n resolve(speaker.result);\r\n });\r\n // if we do not receive a result within the timeout, reject\r\n setTimeout(() => {\r\n reject(\r\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\r\n `Calibration failed to produce a result after ${\r\n timeOut / 1000\r\n } seconds. Please try again.`\r\n )\r\n );\r\n }, timeOut);\r\n });\r\n });\r\n };\r\n\r\n /**\r\n * Called after the peer conncection has been opened.\r\n * Generates a QR code for the connection and displays it.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #showQRCode = () => {\r\n // Get query string, the URL parameters to specify a Listener\r\n const queryStringParameters = {\r\n speakerPeerId: this.peer.id,\r\n isSmartPhone: this.isSmartPhone,\r\n calibrateSoundHz: this.calibrateSoundHz,\r\n calibrateSoundSamplingDesiredBits: this.calibrateSoundSamplingDesiredBits,\r\n };\r\n const queryString = this.queryStringFromObject(queryStringParameters);\r\n const uri = this.siteUrl + queryString;\r\n if (this.isSmartPhone) {\r\n // Display QR code for the participant to scan\r\n const qrCanvas = document.createElement('canvas');\r\n qrCanvas.setAttribute('id', 'qrCanvas');\r\n console.log(uri);\r\n qrcode__WEBPACK_IMPORTED_MODULE_0__.toCanvas(qrCanvas, uri, error => {\r\n if (error) console.error(error);\r\n });\r\n document.getElementById(this.targetElement).appendChild(qrCanvas);\r\n } else {\r\n // show the link to the user\r\n // If specified HTML Id is available, show QR code there\r\n if (document.getElementById(this.targetElement)) {\r\n // const linkTag = document.createElement('a');\r\n // linkTag.setAttribute('href', uri);\r\n // linkTag.innerHTML = 'Click here to start the calibration';\r\n // linkTag.target = '_blank';\r\n // document.getElementById(this.targetElement).appendChild(linkTag);\r\n // document.getElementById(this.targetElement).appendChild(qrCanvas);\r\n\r\n const proceedButton = document.createElement('button');\r\n proceedButton.setAttribute('id', 'calibrationProceedButton');\r\n proceedButton.setAttribute('class', 'btn btn-success');\r\n proceedButton.innerHTML = 'Proceed';\r\n proceedButton.onclick = () => {\r\n // open the link in a new tab\r\n window.open(uri, '_blank');\r\n // remove the button\r\n document.getElementById('calibrationProceedButton').remove();\r\n };\r\n document.getElementById(this.targetElement).appendChild(proceedButton);\r\n }\r\n }\r\n // or just print it to console\r\n console.log('TEST: Peer reachable at: ', uri);\r\n };\r\n\r\n #showSpinner = () => {\r\n const spinner = document.createElement('div');\r\n spinner.className = 'spinner-border ml-auto';\r\n spinner.role = 'status';\r\n spinner.ariaHidden = 'true';\r\n document.getElementById(this.targetElement).appendChild(spinner);\r\n\r\n // clear instructionDisplay\r\n const soundMessage = document.getElementById(this.soundMessageId);\r\n soundMessage.innerHTML = '';\r\n soundMessage.style.display = 'none';\r\n const instructionDisplay = document.getElementById(this.instructionDisplayId);\r\n const background = document.getElementById('background'); // todo: get background id from params\r\n if (instructionDisplay) {\r\n instructionDisplay.innerHTML = '';\r\n instructionDisplay.style.whiteSpace = 'nowrap';\r\n instructionDisplay.style.fontWeight = 'bold';\r\n instructionDisplay.style.width = 'fit-content';\r\n instructionDisplay.innerHTML = _dist_example_i18n__WEBPACK_IMPORTED_MODULE_6__.phrases.RC_soundRecording[\"en-US\"];\r\n let fontSize = 100;\r\n instructionDisplay.style.fontSize = fontSize + 'px';\r\n while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {\r\n fontSize--;\r\n instructionDisplay.style.fontSize = fontSize + 'px';\r\n }\r\n // const p = document.createElement('p');\r\n // // font size\r\n // p.style.fontSize = '1.1rem';\r\n // p.style.fontWeight = 'normal';\r\n // p.style.paddingTop = '20px';\r\n // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];\r\n // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\r\n // instructionDisplay.appendChild(p);\r\n }\r\n\r\n const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);\r\n if (timeToCalibrateDisplay) {\r\n const timeToCalibrateText = _dist_example_i18n__WEBPACK_IMPORTED_MODULE_6__.phrases.RC_howLongToCalibrate[\"en-US\"];\r\n timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\r\n timeToCalibrateDisplay.style.fontWeight = 'normal';\r\n timeToCalibrateDisplay.style.fontSize = '1rem';\r\n // timeToCalibrateDisplay.style.paddingTop = '20px';\r\n }\r\n\r\n // Update title - titleDisplayId\r\n const titleDisplay = document.getElementById(this.titleDisplayId);\r\n if (titleDisplay) {\r\n // replace 5 with 6\r\n titleDisplay.innerHTML = titleDisplay.innerHTML.replace('5', '6');\r\n }\r\n };\r\n\r\n #removeUIElems = () => {\r\n const parent = document.getElementById(this.targetElement);\r\n while (parent.firstChild) {\r\n parent.firstChild.remove();\r\n }\r\n };\r\n\r\n /**\r\n * Called when the peer connection is opened.\r\n * Saves the peer id and calls the QR code generator.\r\n *\r\n * @param peerId - The peer id of the peer connection.\r\n * @param id\r\n * @private\r\n * @example\r\n */\r\n #onPeerOpen = id => {\r\n // Workaround for peer.reconnect deleting previous id\r\n if (id === null) {\r\n console.error('Received null id from peer open');\r\n this.peer.id = this.lastPeerId;\r\n } else {\r\n this.lastPeerId = this.peer.id;\r\n }\r\n\r\n if (id !== this.peer.id) {\r\n console.warn('DEBUG Check you assumption that id === this.peer.id');\r\n }\r\n\r\n this.#showQRCode();\r\n };\r\n\r\n /**\r\n * Called when the peer connection is established.\r\n * Enforces a single connection.\r\n *\r\n * @param connection - The connection object.\r\n * @private\r\n * @example\r\n */\r\n #onPeerConnection = connection => {\r\n // Allow only a single connection\r\n if (this.conn && this.conn.open) {\r\n connection.on('open', () => {\r\n connection.send('Already connected to another client');\r\n setTimeout(() => {\r\n connection.close();\r\n }, 500);\r\n });\r\n return;\r\n }\r\n\r\n this.conn = connection;\r\n console.log('Connected to: ', this.conn.peer);\r\n this.#ready();\r\n };\r\n\r\n /**\r\n * Called when the peer connection is closed.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #onPeerClose = () => {\r\n this.conn = null;\r\n console.log('Connection destroyed');\r\n };\r\n\r\n /**\r\n * Called when the peer connection is disconnected.\r\n * Attempts to reconnect.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #onPeerDisconnected = () => {\r\n console.log('Connection lost. Please reconnect');\r\n\r\n // Workaround for peer.reconnect deleting previous id\r\n this.peer.id = this.lastPeerId;\r\n // eslint-disable-next-line no-underscore-dangle\r\n this.peer._lastServerId = this.lastPeerId;\r\n this.peer.reconnect();\r\n };\r\n\r\n /**\r\n * Called when the peer connection encounters an error.\r\n *\r\n * @param error\r\n * @private\r\n * @example\r\n */\r\n #onPeerError = error => {\r\n // TODO: check if this function is needed or not\r\n console.error(error);\r\n };\r\n\r\n /**\r\n * Called when data is received from the peer connection.\r\n *\r\n * @param data\r\n * @private\r\n * @example\r\n */\r\n #onIncomingData = data => {\r\n // enforce object type\r\n if (\r\n !Object.prototype.hasOwnProperty.call(data, 'name') ||\r\n !Object.prototype.hasOwnProperty.call(data, 'payload')\r\n ) {\r\n console.error('Received malformed data: ', data);\r\n return;\r\n }\r\n\r\n switch (data.name) {\r\n case 'samplingRate':\r\n this.ac.setSamplingRates(data.payload);\r\n break;\r\n case 'sampleSize':\r\n this.ac.setSampleSize(data.payload);\r\n break;\r\n case 'deviceType':\r\n this.ac.setDeviceType(data.payload);\r\n break;\r\n case 'deviceName':\r\n this.ac.setDeviceName(data.payload);\r\n break;\r\n case 'deviceInfo':\r\n this.ac.setDeviceInfo(data.payload);\r\n console.log('Received device info from listener: ', data.payload);\r\n break;\r\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.UnsupportedDeviceError.name:\r\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.MissingSpeakerIdError.name:\r\n throw data.payload;\r\n break;\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Called when the peer connection is #ready.\r\n *\r\n * @private\r\n * @example\r\n */\r\n #ready = () => {\r\n // Perform callback with data\r\n this.conn.on('data', this.#onIncomingData);\r\n this.conn.on('close', () => {\r\n console.log('Connection reset<br>Awaiting connection...');\r\n this.conn = null;\r\n });\r\n };\r\n\r\n /** .\r\n * .\r\n * .\r\n * Debug method for downloading the recorded audio\r\n *\r\n * @public\r\n * @example\r\n */\r\n downloadData = () => {\r\n this.ac.downloadData();\r\n };\r\n}\r\n\r\n/* \r\nReferenced links:\r\nhttps://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676\r\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\r\nhttps://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]\r\n*/\r\n\r\n/* harmony default export */ __webpack_exports__[\"default\"] = (Speaker);\r\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/speaker.js?");
|
|
800
800
|
|
|
801
801
|
/***/ }),
|
|
802
802
|
|
package/package.json
CHANGED
|
@@ -16,8 +16,9 @@ class Listener extends AudioPeer {
|
|
|
16
16
|
*/
|
|
17
17
|
constructor(params) {
|
|
18
18
|
super(params);
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
this.deviceInfoFromUser = params.deviceInfoFromUser
|
|
20
|
+
? params.deviceInfoFromUser
|
|
21
|
+
: {modelNumber: '', modelName: ''};
|
|
21
22
|
this.startTime = Date.now();
|
|
22
23
|
this.receiverPeerId = null;
|
|
23
24
|
|
|
@@ -166,8 +167,9 @@ class Listener extends AudioPeer {
|
|
|
166
167
|
deviceInfo['PlatformName'] = data.device['platformname'];
|
|
167
168
|
deviceInfo['PlatformVersion'] = data.device['platformversion'];
|
|
168
169
|
deviceInfo['DeviceType'] = data.device['devicetype'];
|
|
169
|
-
deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;
|
|
170
|
+
// deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;
|
|
170
171
|
});
|
|
172
|
+
deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;
|
|
171
173
|
this.conn.send({
|
|
172
174
|
name: 'deviceInfo',
|
|
173
175
|
payload: deviceInfo,
|
|
@@ -420,6 +420,8 @@ class Speaker extends AudioPeer {
|
|
|
420
420
|
break;
|
|
421
421
|
case 'deviceInfo':
|
|
422
422
|
this.ac.setDeviceInfo(data.payload);
|
|
423
|
+
console.log('Received device info from listener: ', data.payload);
|
|
424
|
+
break;
|
|
423
425
|
case UnsupportedDeviceError.name:
|
|
424
426
|
case MissingSpeakerIdError.name:
|
|
425
427
|
throw data.payload;
|