speaker-calibration 2.2.125 → 2.2.126
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
|
@@ -61,8 +61,10 @@ switch (isSmartPhone) {
|
|
|
61
61
|
const externalMicList = ['UMIK', 'Airpods', 'Bluetooth'];
|
|
62
62
|
try {
|
|
63
63
|
const stream = await navigator.mediaDevices.getUserMedia({audio: true});
|
|
64
|
+
console.log(stream);
|
|
64
65
|
if (stream) {
|
|
65
66
|
const devices = await navigator.mediaDevices.enumerateDevices();
|
|
67
|
+
console.log(devices);
|
|
66
68
|
const mics = devices.filter(device => device.kind === 'audioinput');
|
|
67
69
|
mics.forEach(mic => {
|
|
68
70
|
if (externalMicList.some(externalMic => mic.label.includes(externalMic))) {
|
|
@@ -88,7 +90,9 @@ switch (isSmartPhone) {
|
|
|
88
90
|
} catch (err) {
|
|
89
91
|
console.log(err);
|
|
90
92
|
}
|
|
93
|
+
console.log(lock);
|
|
91
94
|
window.listener = new speakerCalibrator.Listener(listenerParameters);
|
|
95
|
+
console.log(window.listener);
|
|
92
96
|
if (lock) {
|
|
93
97
|
lock.release();
|
|
94
98
|
}
|
package/dist/main.js
CHANGED
|
@@ -785,7 +785,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var peer
|
|
|
785
785
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
786
786
|
|
|
787
787
|
"use strict";
|
|
788
|
-
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\n\n\n\n/**\n * @class Handles the listener's side of the connection. Responsible for getting access to user's microphone,\n * and initiating a call to the Speaker.\n * @augments AudioPeer\n */\nclass Listener extends _audioPeer__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n /**\n * Takes a target element where html elements will be appended.\n *\n * @param params - See type definition for initParameters.\n * @example\n */\n constructor(params) {\n super(params);\n this.microphoneFromAPI = params.microphoneFromAPI ? params.microphoneFromAPI : '';\n this.microphoneDeviceId = params.microphoneDeviceId ? params.microphoneDeviceId : '';\n // this.deviceInfoFromUser = params.deviceInfoFromUser\n // ? params.deviceInfoFromUser\n // : {modelNumber: '', modelName: ''};\n this.startTime = Date.now();\n this.receiverPeerId = null;\n\n const urlParameters = this.parseURLSearchParams();\n this.calibrateSoundHz =\n urlParameters.calibrateSoundHz !== null && urlParameters.calibrateSoundHz !== undefined\n ? urlParameters.calibrateSoundHz\n : 48000;\n this.calibrateSoundSamplingDesiredBits =\n urlParameters.calibrateSoundSamplingDesiredBits !== null &&\n urlParameters.calibrateSoundSamplingDesiredBits !== undefined\n ? urlParameters.calibrateSoundSamplingDesiredBits\n : 24;\n this.speakerPeerId = urlParameters.speakerPeerId;\n\n this.peer.on('open', this.onPeerOpen);\n this.peer.on('connection', this.onPeerConnection);\n this.peer.on('disconnected', this.onPeerDisconnected);\n this.peer.on('close', this.onPeerClose);\n this.peer.on('error', this.onPeerError);\n }\n\n onPeerOpen = id => {\n this.displayUpdate('Listener - onPeerOpen');\n // Workaround for peer.reconnect deleting previous id\n\n if (id === null) {\n this.displayUpdate('Received null id from peer open');\n this.peer.id = this.lastPeerId;\n } else {\n this.lastPeerId = this.peer.id;\n }\n\n this.join();\n };\n\n onPeerConnection = connection => {\n this.displayUpdate('Listener - onPeerConnection');\n // Disallow incoming connections\n connection.on('open', () => {\n connection.send('Sender does not accept incoming connections');\n setTimeout(() => {\n connection.close();\n }, 500);\n });\n };\n\n onConnData = data => {\n this.displayUpdate('Listener - onConnData');\n const hasSpeakerID = Object.prototype.hasOwnProperty.call(data, 'speakerPeerId');\n if (!hasSpeakerID) {\n this.displayUpdate('Error in parsing data received! Must set \"speakerPeerId\" property');\n throw new _peerErrors__WEBPACK_IMPORTED_MODULE_1__.MissingSpeakerIdError('Must set \"speakerPeerId\" property');\n } else {\n // this.conn.close();\n this.displayUpdate(this.speakerPeerId);\n this.speakerPeerId = data.speakerPeerId;\n const newParams = {\n speakerPeerId: this.speakerPeerId,\n };\n /*\n FUTURE does this limit usable environments?\n ie does this work if internet is lost after initial page load?\n */\n window.location.search = this.queryStringFromObject(newParams); // Redirect to correctly constructed keypad page\n }\n };\n\n join = async () => {\n this.displayUpdate('Listener - join');\n /**\n * Create the connection between the two Peers.\n *\n * Sets up callbacks that handle any events related to the\n * connection and data received on it.\n */\n // Close old connection\n if (this.conn) {\n this.displayUpdate('Closing old connection');\n this.conn.close();\n }\n\n // Create connection to destination peer specified by the query param\n this.displayUpdate(`Creating connection to: ${this.speakerPeerId}`);\n this.conn = this.peer.connect(this.speakerPeerId, {\n reliable: true,\n });\n\n this.displayUpdate('Created connection');\n this.conn.on('open', async () => {\n this.displayUpdate('Listener - conn open');\n await this.getDeviceInfo();\n // this.sendSamplingRate();\n await this.openAudioStream();\n });\n\n // Handle incoming data (messages only since this is the signal sender)\n this.conn.on('data', this.onConnData);\n this.conn.on('close', () => {\n console.log('Connection closed');\n });\n };\n\n getMobileOS = () => {\n const ua = navigator.userAgent;\n if (/android/i.test(ua)) {\n return 'Android';\n }\n if (\n /iPad|iPhone|iPod/.test(ua) ||\n ((navigator?.userAgentData?.platform || navigator?.platform) === 'MacIntel' &&\n navigator.maxTouchPoints > 1)\n ) {\n return 'iOS';\n }\n return 'Other';\n };\n\n sendSamplingRate = sampleRate => {\n this.displayUpdate('Listener - sendSamplingRate');\n this.conn.send({\n name: 'samplingRate',\n payload: sampleRate,\n });\n };\n\n sendSampleSize = sampleSize => {\n this.displayUpdate('Listener - sendSampleSize');\n this.conn.send({\n name: 'sampleSize',\n payload: sampleSize,\n });\n };\n\n getDeviceInfo = async () => {\n try {\n const deviceInfo = {};\n fod.complete(function (data) {\n deviceInfo['IsMobile'] = data.device['ismobile'];\n deviceInfo['HardwareName'] = data.device['hardwarename'];\n deviceInfo['HardwareFamily'] = data.device['hardwarefamily'];\n deviceInfo['HardwareModel'] = data.device['hardwaremodel'];\n deviceInfo['OEM'] = data.device['oem'];\n deviceInfo['HardwareModelVariants'] = data.device['hardwaremodelvariants'];\n deviceInfo['DeviceId'] = data.device['deviceid'];\n deviceInfo['PlatformName'] = data.device['platformname'];\n deviceInfo['PlatformVersion'] = data.device['platformversion'];\n deviceInfo['DeviceType'] = data.device['devicetype'];\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\n });\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\n deviceInfo['microphoneFromAPI'] = this.microphoneFromAPI;\n deviceInfo['microphoneDeviceId'] = this.microphoneDeviceId;\n deviceInfo['screenWidth'] = window.screen.width;\n deviceInfo['screenHeight'] = window.screen.height;\n console.log('deviceInfo Inside getDeviceInfo: ', deviceInfo);\n this.conn.send({\n name: 'deviceInfo',\n payload: deviceInfo,\n });\n return deviceInfo;\n } catch (error) {\n console.error('Error fetching or executing script:', error.message);\n return null;\n }\n };\n\n applyHQTrackConstraints = async stream => {\n // Contraint the incoming audio to the sampling rate we want\n\n const track = stream.getAudioTracks()[0];\n const capabilities = track.getCapabilities();\n\n this.displayUpdate(\n `Listener Track Capabilities - ${JSON.stringify(capabilities, undefined, 2)}`\n );\n\n const constraints = track.getConstraints();\n\n if (capabilities.echoCancellation) {\n constraints.echoCancellation = false;\n }\n\n if (capabilities.sampleRate) {\n constraints.sampleRate = this.calibrateSoundHz;\n }\n\n if (capabilities.sampleSize) {\n constraints.sampleSize = this.calibrateSoundSamplingDesiredBits;\n }\n\n if (capabilities.channelCount) {\n constraints.channelCount = 1;\n }\n\n this.displayUpdate(`Listener Track Constraints - ${JSON.stringify(constraints, undefined, 2)}`);\n\n // await the promise\n try {\n await track.applyConstraints(constraints);\n } catch (err) {\n console.error(err);\n this.displayUpdate(`Error applying constraints to track: ${err}`);\n }\n\n const settings = track.getSettings();\n this.displayUpdate(`Listener Track Settings - ${JSON.stringify(settings, undefined, 2)}`);\n return settings;\n };\n\n getMediaDevicesAudioContraints = () => {\n const availableConstraints = navigator.mediaDevices.getSupportedConstraints();\n\n this.displayUpdate(\n `Listener MediaDevices Available Contraints - ${JSON.stringify(\n availableConstraints,\n undefined,\n 2\n )}`\n );\n\n const contraints = {\n // ...(availableConstraints.echoCancellation && availableConstraints.echoCancellation == true\n // ? {echoCancellation: {exact: false}}\n // : {}),\n ...(availableConstraints.sampleRate && availableConstraints.sampleRate == true\n ? {sampleRate: {ideal: this.calibrateSoundHz}}\n : {}),\n ...(availableConstraints.sampleSize && availableConstraints.sampleSize == true\n ? {sampleSize: {ideal: this.calibrateSoundSamplingDesiredBits}}\n : {}),\n ...(availableConstraints.channelCount && availableConstraints.channelCount == true\n ? {channelCount: {exact: 1}}\n : {}),\n echoCancellation: false,\n noiseSuppression: false,\n autoGainControl: false,\n };\n\n if (this.microphoneDeviceId !== '') {\n contraints.deviceId = {exact: this.microphoneDeviceId};\n }\n\n console.log(contraints);\n\n this.displayUpdate(\n `Listener MediaDevices Contraints - ${JSON.stringify(contraints, undefined, 2)}`\n );\n\n return contraints;\n };\n\n openAudioStream = async () => {\n this.displayUpdate('Listener - openAudioStream');\n const mobileOS = this.getMobileOS();\n if (false) {}\n\n const audioContext = new (window.AudioContext || window.webkitAudioContext)();\n navigator.mediaDevices\n .getUserMedia({\n audio: this.getMediaDevicesAudioContraints(),\n video: false,\n })\n .then(stream => {\n const sourceNode = audioContext.createMediaStreamSource(stream);\n const sampleRate = sourceNode.context.sampleRate;\n console.log(sampleRate);\n const audioBuffer = audioContext.createBuffer(1, 1, sampleRate);\n const sampleSizeInBits = audioBuffer.getChannelData(0).BYTES_PER_ELEMENT * 8;\n console.log(sampleSizeInBits);\n audioContext.close();\n this.applyHQTrackConstraints(stream)\n .then(settings => {\n this.sendSamplingRate(sampleRate);\n // let sampleSize = settings.sampleSize;\n // if (!sampleSize){\n // sampleSize = this.calibrateSoundSamplingDesiredBits;\n // }\n this.sendSampleSize(sampleSizeInBits);\n this.peer.call(this.speakerPeerId, stream); // one-way call\n this.displayUpdate('Listener - openAudioStream');\n })\n .catch(err => {\n console.log(err);\n this.displayUpdate(\n `Listener - Error in applyHQTrackConstraints - ${JSON.stringify(err, undefined, 2)}`\n );\n });\n })\n .catch(err => {\n console.error(err);\n this.displayUpdate(\n `Listener - Error in getUserMedia - ${JSON.stringify(err, undefined, 2)}`\n );\n });\n };\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Listener);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/listener.js?");
|
|
788
|
+
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\n\n\n\n/**\n * @class Handles the listener's side of the connection. Responsible for getting access to user's microphone,\n * and initiating a call to the Speaker.\n * @augments AudioPeer\n */\nclass Listener extends _audioPeer__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n /**\n * Takes a target element where html elements will be appended.\n *\n * @param params - See type definition for initParameters.\n * @example\n */\n constructor(params) {\n super(params);\n this.microphoneFromAPI = params.microphoneFromAPI ? params.microphoneFromAPI : '';\n this.microphoneDeviceId = params.microphoneDeviceId ? params.microphoneDeviceId : '';\n // this.deviceInfoFromUser = params.deviceInfoFromUser\n // ? params.deviceInfoFromUser\n // : {modelNumber: '', modelName: ''};\n this.startTime = Date.now();\n this.receiverPeerId = null;\n\n const urlParameters = this.parseURLSearchParams();\n this.calibrateSoundHz =\n urlParameters.calibrateSoundHz !== null && urlParameters.calibrateSoundHz !== undefined\n ? urlParameters.calibrateSoundHz\n : 48000;\n this.calibrateSoundSamplingDesiredBits =\n urlParameters.calibrateSoundSamplingDesiredBits !== null &&\n urlParameters.calibrateSoundSamplingDesiredBits !== undefined\n ? urlParameters.calibrateSoundSamplingDesiredBits\n : 24;\n this.speakerPeerId = urlParameters.speakerPeerId;\n\n this.peer.on('open', this.onPeerOpen);\n this.peer.on('connection', this.onPeerConnection);\n this.peer.on('disconnected', this.onPeerDisconnected);\n this.peer.on('close', this.onPeerClose);\n this.peer.on('error', this.onPeerError);\n }\n\n onPeerOpen = id => {\n this.displayUpdate('Listener - onPeerOpen');\n // Workaround for peer.reconnect deleting previous id\n\n if (id === null) {\n this.displayUpdate('Received null id from peer open');\n this.peer.id = this.lastPeerId;\n } else {\n this.lastPeerId = this.peer.id;\n }\n\n this.join();\n };\n\n onPeerConnection = connection => {\n this.displayUpdate('Listener - onPeerConnection');\n // Disallow incoming connections\n connection.on('open', () => {\n connection.send('Sender does not accept incoming connections');\n setTimeout(() => {\n connection.close();\n }, 500);\n });\n };\n\n onConnData = data => {\n this.displayUpdate('Listener - onConnData');\n const hasSpeakerID = Object.prototype.hasOwnProperty.call(data, 'speakerPeerId');\n if (!hasSpeakerID) {\n this.displayUpdate('Error in parsing data received! Must set \"speakerPeerId\" property');\n throw new _peerErrors__WEBPACK_IMPORTED_MODULE_1__.MissingSpeakerIdError('Must set \"speakerPeerId\" property');\n } else {\n // this.conn.close();\n this.displayUpdate(this.speakerPeerId);\n this.speakerPeerId = data.speakerPeerId;\n const newParams = {\n speakerPeerId: this.speakerPeerId,\n };\n /*\n FUTURE does this limit usable environments?\n ie does this work if internet is lost after initial page load?\n */\n window.location.search = this.queryStringFromObject(newParams); // Redirect to correctly constructed keypad page\n }\n };\n\n join = async () => {\n this.displayUpdate('Listener - join');\n /**\n * Create the connection between the two Peers.\n *\n * Sets up callbacks that handle any events related to the\n * connection and data received on it.\n */\n // Close old connection\n if (this.conn) {\n this.displayUpdate('Closing old connection');\n this.conn.close();\n }\n\n // Create connection to destination peer specified by the query param\n this.displayUpdate(`Creating connection to: ${this.speakerPeerId}`);\n this.conn = this.peer.connect(this.speakerPeerId, {\n reliable: true,\n });\n\n this.displayUpdate('Created connection');\n this.conn.on('open', async () => {\n this.displayUpdate('Listener - conn open');\n await this.getDeviceInfo();\n // this.sendSamplingRate();\n await this.openAudioStream();\n });\n\n // Handle incoming data (messages only since this is the signal sender)\n this.conn.on('data', this.onConnData);\n this.conn.on('close', () => {\n console.log('Connection closed');\n });\n };\n\n getMobileOS = () => {\n const ua = navigator.userAgent;\n if (/android/i.test(ua)) {\n return 'Android';\n }\n if (\n /iPad|iPhone|iPod/.test(ua) ||\n ((navigator?.userAgentData?.platform || navigator?.platform) === 'MacIntel' &&\n navigator.maxTouchPoints > 1)\n ) {\n return 'iOS';\n }\n return 'Other';\n };\n\n sendSamplingRate = sampleRate => {\n this.displayUpdate('Listener - sendSamplingRate');\n this.conn.send({\n name: 'samplingRate',\n payload: sampleRate,\n });\n };\n\n sendSampleSize = sampleSize => {\n this.displayUpdate('Listener - sendSampleSize');\n this.conn.send({\n name: 'sampleSize',\n payload: sampleSize,\n });\n };\n\n getDeviceInfo = async () => {\n try {\n const deviceInfo = {};\n fod.complete(function (data) {\n deviceInfo['IsMobile'] = data.device['ismobile'];\n deviceInfo['HardwareName'] = data.device['hardwarename'];\n deviceInfo['HardwareFamily'] = data.device['hardwarefamily'];\n deviceInfo['HardwareModel'] = data.device['hardwaremodel'];\n deviceInfo['OEM'] = data.device['oem'];\n deviceInfo['HardwareModelVariants'] = data.device['hardwaremodelvariants'];\n deviceInfo['DeviceId'] = data.device['deviceid'];\n deviceInfo['PlatformName'] = data.device['platformname'];\n deviceInfo['PlatformVersion'] = data.device['platformversion'];\n deviceInfo['DeviceType'] = data.device['devicetype'];\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\n });\n // deviceInfo['deviceInfoFromUser'] = this.deviceInfoFromUser;\n deviceInfo['microphoneFromAPI'] = this.microphoneFromAPI;\n deviceInfo['microphoneDeviceId'] = this.microphoneDeviceId;\n deviceInfo['screenWidth'] = window.screen.width;\n deviceInfo['screenHeight'] = window.screen.height;\n console.log('deviceInfo Inside getDeviceInfo: ', deviceInfo);\n this.conn.send({\n name: 'deviceInfo',\n payload: deviceInfo,\n });\n return deviceInfo;\n } catch (error) {\n console.error('Error fetching or executing script:', error.message);\n return null;\n }\n };\n\n applyHQTrackConstraints = async stream => {\n // Contraint the incoming audio to the sampling rate we want\n\n const track = stream.getAudioTracks()[0];\n const capabilities = track.getCapabilities();\n\n this.displayUpdate(\n `Listener Track Capabilities - ${JSON.stringify(capabilities, undefined, 2)}`\n );\n\n const constraints = track.getConstraints();\n\n if (capabilities.echoCancellation) {\n constraints.echoCancellation = false;\n }\n\n if (capabilities.sampleRate) {\n constraints.sampleRate = this.calibrateSoundHz;\n }\n\n if (capabilities.sampleSize) {\n constraints.sampleSize = this.calibrateSoundSamplingDesiredBits;\n }\n\n if (capabilities.channelCount) {\n constraints.channelCount = 1;\n }\n\n this.displayUpdate(`Listener Track Constraints - ${JSON.stringify(constraints, undefined, 2)}`);\n\n // await the promise\n try {\n await track.applyConstraints(constraints);\n } catch (err) {\n console.error(err);\n this.displayUpdate(`Error applying constraints to track: ${err}`);\n }\n\n const settings = track.getSettings();\n this.displayUpdate(`Listener Track Settings - ${JSON.stringify(settings, undefined, 2)}`);\n return settings;\n };\n\n getMediaDevicesAudioContraints = () => {\n const availableConstraints = navigator.mediaDevices.getSupportedConstraints();\n\n this.displayUpdate(\n `Listener MediaDevices Available Contraints - ${JSON.stringify(\n availableConstraints,\n undefined,\n 2\n )}`\n );\n\n const contraints = {\n // ...(availableConstraints.echoCancellation && availableConstraints.echoCancellation == true\n // ? {echoCancellation: {exact: false}}\n // : {}),\n ...(availableConstraints.sampleRate && availableConstraints.sampleRate == true\n ? {sampleRate: {ideal: this.calibrateSoundHz}}\n : {}),\n ...(availableConstraints.sampleSize && availableConstraints.sampleSize == true\n ? {sampleSize: {ideal: this.calibrateSoundSamplingDesiredBits}}\n : {}),\n ...(availableConstraints.channelCount && availableConstraints.channelCount == true\n ? {channelCount: {exact: 1}}\n : {}),\n echoCancellation: false,\n noiseSuppression: false,\n autoGainControl: false,\n };\n\n if (this.microphoneDeviceId !== '') {\n contraints.deviceId = {exact: this.microphoneDeviceId};\n }\n\n console.log(contraints);\n\n this.displayUpdate(\n `Listener MediaDevices Contraints - ${JSON.stringify(contraints, undefined, 2)}`\n );\n\n return contraints;\n };\n\n openAudioStream = async () => {\n this.displayUpdate('Listener - openAudioStream');\n const mobileOS = this.getMobileOS();\n if (false) {}\n\n navigator.mediaDevices\n .getUserMedia({\n audio: this.getMediaDevicesAudioContraints(),\n video: false,\n })\n .then(stream => {\n this.applyHQTrackConstraints(stream)\n .then(settings => {\n console.log(settings);\n this.sendSamplingRate(sampleRate);\n let sampleSize = settings.sampleSize;\n if (!sampleSize){\n sampleSize = this.calibrateSoundSamplingDesiredBits;\n }\n this.sendSampleSize(sampleSize);\n this.peer.call(this.speakerPeerId, stream); // one-way call\n this.displayUpdate('Listener - openAudioStream');\n })\n .catch(err => {\n console.log(err);\n this.displayUpdate(\n `Listener - Error in applyHQTrackConstraints - ${JSON.stringify(err, undefined, 2)}`\n );\n });\n })\n .catch(err => {\n console.error(err);\n this.displayUpdate(\n `Listener - Error in getUserMedia - ${JSON.stringify(err, undefined, 2)}`\n );\n });\n };\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Listener);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/listener.js?");
|
|
789
789
|
|
|
790
790
|
/***/ }),
|
|
791
791
|
|
|
@@ -807,7 +807,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
|
|
|
807
807
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
808
808
|
|
|
809
809
|
"use strict";
|
|
810
|
-
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 _dist_example_i18n__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../dist/example/i18n */ \"./dist/example/i18n.js\");\n\n\n\n\n\n\n\n/**\n * @class Handles the speaker's side of the connection. Responsible for initiating the connection,\n * rendering the QRCode, and answering the call.\n * @augments AudioPeer\n */\nclass Speaker extends _audioPeer__WEBPACK_IMPORTED_MODULE_1__[\"default\"] {\n /**\n * Takes the url of the current site and a target element where html elements will be appended.\n *\n * @param params - See type definition for initParameters.\n * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.\n * @param CalibratorInstance\n * @example\n */\n constructor(params, CalibratorInstance) {\n super(params);\n this.language = params?.language ?? 'en-US';\n this.siteUrl += '/listener?';\n this.ac = CalibratorInstance;\n this.result = null;\n this.debug = params?.debug ?? false;\n this.isSmartPhone = params?.isSmartPhone ?? false;\n this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;\n this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;\n this.instructionDisplayId = params?.instructionDisplayId ?? '';\n this.soundSubtitleId = params?.soundSubtitleId ?? '';\n this.timeToCalibrateDisplay = params?.timeToCalibrateId ?? '';\n this.soundMessageId = params?.soundMessageId ?? '';\n this.titleDisplayId = params?.titleDisplayId ?? '';\n this.timeToCalibrate = params?.timeToCalibrate ?? 10;\n\n /* Set up callbacks that handle any events related to our peer object. */\n this.peer.on('open', this.#onPeerOpen);\n this.peer.on('connection', this.#onPeerConnection);\n this.peer.on('close', this.onPeerClose);\n this.peer.on('disconnected', this.#onPeerDisconnected);\n this.peer.on('error', this.#onPeerError);\n }\n /**\n * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.\n *\n * @param params - The parameters to be passed to the peer object.\n * @param Calibrator - The class that defines the calibration process.\n * @param CalibratorInstance\n * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).\n * @public\n * @example\n */\n static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {\n window.speaker = new Speaker(params, CalibratorInstance);\n const {speaker} = window;\n\n // wrap the calibration process in a promise so we can await it\n return new Promise((resolve, reject) => {\n // when a call is received\n speaker.peer.on('call', async call => {\n // Answer the call (one way)\n\n call.answer();\n speaker.#removeUIElems();\n speaker.#showSpinner();\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\n // when we start receiving audio\n call.on('stream', async stream => {\n window.localStream = stream;\n window.localAudio.srcObject = stream;\n window.localAudio.autoplay = false;\n\n // if the sinkSamplingRate is not set sleep\n while (!speaker.ac.sampleRatesSet()) {\n console.log('SinkSamplingRate is undefined, sleeping');\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\n }\n\n if (params.displayUpdate) {\n params.displayUpdate.style.display = '';\n }\n\n // resolve when we have a result\n speaker.result = await speaker.ac.startCalibration(\n stream,\n params.gainValues,\n params.ICalib,\n params.knownIR,\n params.microphoneName,\n params.calibrateSoundCheck,\n params.isSmartPhone,\n params.calibrateSoundBurstDb,\n params.calibrateSoundBurstRepeats,\n params.calibrateSoundBurstSec,\n params.calibrateSoundBurstsWarmup,\n params.calibrateSoundHz,\n params.calibrateSoundIRSec,\n params.calibrateSoundIIRSec,\n params.calibrateSound1000HzPreSec,\n params.calibrateSound1000HzSec,\n params.calibrateSound1000HzPostSec,\n params.calibrateSoundBackgroundSecs,\n params.calibrateSoundSmoothOctaves,\n params.calibrateSoundPowerBinDesiredSec,\n params.calibrateSoundPowerDbSDToleratedDb,\n params.micManufacturer,\n params.micSerialNumber,\n params.micModelNumber,\n params.micModelName,\n params.calibrateMicrophonesBool,\n params.authorEmails,\n params.webAudioDeviceNames,\n params.IDsToSaveInSoundProfileLibrary,\n params.restartButton,\n params.calibrateSoundLimit\n );\n speaker.#removeUIElems();\n resolve(speaker.result);\n });\n // if we do not receive a result within the timeout, reject\n setTimeout(() => {\n reject(\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\n `Calibration failed to produce a result after ${\n timeOut / 1000\n } seconds. Please try again.`\n )\n );\n }, timeOut);\n });\n });\n };\n\n static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {\n window.speaker = new Speaker(params, CalibratorInstance);\n const {speaker} = window;\n\n // wrap the calibration process in a promise so we can await it\n return new Promise((resolve, reject) => {\n // when a call is received\n speaker.peer.on('call', async call => {\n // Answer the call (one way)\n call.answer();\n speaker.#removeUIElems();\n speaker.#showSpinner();\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\n // when we start receiving audio\n call.on('stream', async stream => {\n window.localStream = stream;\n window.localAudio.srcObject = stream;\n window.localAudio.autoplay = false;\n\n // if the sinkSamplingRate is not set sleep\n while (!speaker.ac.sampleRatesSet()) {\n console.log('SinkSamplingRate is undefined, sleeping');\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\n }\n // resolve when we have a result\n speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);\n speaker.#removeUIElems();\n resolve(speaker.result);\n });\n // if we do not receive a result within the timeout, reject\n setTimeout(() => {\n reject(\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\n `Calibration failed to produce a result after ${\n timeOut / 1000\n } seconds. Please try again.`\n )\n );\n }, timeOut);\n });\n });\n };\n\n /**\n * Called after the peer conncection has been opened.\n * Generates a QR code for the connection and displays it.\n *\n * @private\n * @example\n */\n #showQRCode = () => {\n // Get query string, the URL parameters to specify a Listener\n const queryStringParameters = {\n speakerPeerId: this.peer.id,\n isSmartPhone: this.isSmartPhone,\n calibrateSoundHz: this.calibrateSoundHz,\n calibrateSoundSamplingDesiredBits: this.calibrateSoundSamplingDesiredBits,\n lang: this.language,\n };\n const queryString = this.queryStringFromObject(queryStringParameters);\n const uri = this.siteUrl + queryString;\n if (this.isSmartPhone) {\n // Display QR code for the participant to scan\n const qrCanvas = document.createElement('canvas');\n qrCanvas.setAttribute('id', 'qrCanvas');\n console.log(uri);\n qrcode__WEBPACK_IMPORTED_MODULE_0__.toCanvas(qrCanvas, uri, error => {\n if (error) console.error(error);\n });\n const qrImage = new Image(400, 400);\n qrImage.setAttribute('id', 'compatibilityCheckQRImage');\n qrImage.style.zIndex = Infinity;\n qrImage.style.width = 400;\n qrImage.style.height = 400;\n qrImage.style.aspectRatio = 1;\n qrImage.src = qrCanvas.toDataURL();\n qrImage.style.maxHeight = '150px';\n qrImage.style.maxWidth = '150px';\n document.getElementById(this.targetElement).appendChild(qrImage);\n } else {\n // show the link to the user\n // If specified HTML Id is available, show QR code there\n if (document.getElementById(this.targetElement)) {\n // const linkTag = document.createElement('a');\n // linkTag.setAttribute('href', uri);\n // linkTag.innerHTML = 'Click here to start the calibration';\n // linkTag.target = '_blank';\n // document.getElementById(this.targetElement).appendChild(linkTag);\n // document.getElementById(this.targetElement).appendChild(qrCanvas);\n\n const proceedButton = document.createElement('button');\n proceedButton.setAttribute('id', 'calibrationProceedButton');\n proceedButton.setAttribute('class', 'btn btn-success');\n proceedButton.innerHTML = 'Proceed';\n proceedButton.onclick = () => {\n // open the link in a new tab\n window.open(uri, '_blank');\n // remove the button\n document.getElementById('calibrationProceedButton').remove();\n };\n document.getElementById(this.targetElement).appendChild(proceedButton);\n }\n }\n // or just print it to console\n console.log('TEST: Peer reachable at: ', uri);\n };\n\n #showSpinner = () => {\n const spinner = document.createElement('div');\n spinner.className = 'spinner-border ml-auto';\n spinner.role = 'status';\n spinner.ariaHidden = 'true';\n document.getElementById(this.targetElement).appendChild(spinner);\n\n // clear instructionDisplay\n const soundMessage = document.getElementById(this.soundMessageId);\n soundMessage.innerHTML = '';\n soundMessage.style.display = 'none';\n const instructionDisplay = document.getElementById(this.instructionDisplayId);\n const background = document.getElementById('background'); // todo: get background id from params\n const subtitle = document.getElementById(this.soundSubtitleId);\n if (subtitle) {\n subtitle.innerHTML = '';\n }\n if (instructionDisplay) {\n instructionDisplay.innerHTML = '';\n instructionDisplay.style.whiteSpace = 'nowrap';\n instructionDisplay.style.fontWeight = 'bold';\n instructionDisplay.style.width = 'fit-content';\n instructionDisplay.innerHTML = _dist_example_i18n__WEBPACK_IMPORTED_MODULE_4__.phrases.RC_soundRecording[this.language];\n let fontSize = 100;\n instructionDisplay.style.fontSize = fontSize + 'px';\n while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {\n fontSize--;\n instructionDisplay.style.fontSize = fontSize + 'px';\n }\n // const p = document.createElement('p');\n // // font size\n // p.style.fontSize = '1.1rem';\n // p.style.fontWeight = 'normal';\n // p.style.paddingTop = '20px';\n // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];\n // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\n // instructionDisplay.appendChild(p);\n }\n\n const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);\n if (timeToCalibrateDisplay) {\n const timeToCalibrateText = _dist_example_i18n__WEBPACK_IMPORTED_MODULE_4__.phrases.RC_howLongToCalibrate[this.language];\n timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\n timeToCalibrateDisplay.style.fontWeight = 'normal';\n timeToCalibrateDisplay.style.fontSize = '1rem';\n // timeToCalibrateDisplay.style.paddingTop = '20px';\n }\n\n // Update title - titleDisplayId\n const titleDisplay = document.getElementById(this.titleDisplayId);\n if (titleDisplay) {\n // replace 5 with 6\n titleDisplay.innerHTML = this.isSmartPhone\n ? titleDisplay.innerHTML.replace('2', '3')\n : titleDisplay.innerHTML.replace('4', '5');\n }\n };\n\n #removeUIElems = () => {\n const parent = document.getElementById(this.targetElement);\n while (parent.firstChild) {\n parent.firstChild.remove();\n }\n };\n\n /**\n * Called when the peer connection is opened.\n * Saves the peer id and calls the QR code generator.\n *\n * @param peerId - The peer id of the peer connection.\n * @param id\n * @private\n * @example\n */\n #onPeerOpen = id => {\n // Workaround for peer.reconnect deleting previous id\n if (id === null) {\n console.error('Received null id from peer open');\n this.peer.id = this.lastPeerId;\n } else {\n this.lastPeerId = this.peer.id;\n }\n\n if (id !== this.peer.id) {\n console.warn('DEBUG Check you assumption that id === this.peer.id');\n }\n\n this.#showQRCode();\n };\n\n /**\n * Called when the peer connection is established.\n * Enforces a single connection.\n *\n * @param connection - The connection object.\n * @private\n * @example\n */\n #onPeerConnection = connection => {\n // Allow only a single connection\n if (this.conn && this.conn.open) {\n connection.on('open', () => {\n connection.send('Already connected to another client');\n setTimeout(() => {\n connection.close();\n }, 500);\n });\n return;\n }\n\n this.conn = connection;\n console.log('Connected to: ', this.conn.peer);\n this.#ready();\n };\n\n /**\n * Called when the peer connection is closed.\n *\n * @private\n * @example\n */\n onPeerClose = () => {\n this.conn = null;\n console.log('Connection destroyed');\n };\n\n static closeConnection = () => {\n this.conn = null;\n console.log('Connection destroyed');\n };\n\n /**\n * Called when the peer connection is disconnected.\n * Attempts to reconnect.\n *\n * @private\n * @example\n */\n #onPeerDisconnected = () => {\n console.log('Connection lost. Please reconnect');\n\n // Workaround for peer.reconnect deleting previous id\n this.peer.id = this.lastPeerId;\n // eslint-disable-next-line no-underscore-dangle\n this.peer._lastServerId = this.lastPeerId;\n this.peer.reconnect();\n };\n\n /**\n * Called when the peer connection encounters an error.\n *\n * @param error\n * @private\n * @example\n */\n #onPeerError = error => {\n // TODO: check if this function is needed or not\n console.error(error);\n };\n\n /**\n * Called when data is received from the peer connection.\n *\n * @param data\n * @private\n * @example\n */\n #onIncomingData = data => {\n // enforce object type\n if (\n !Object.prototype.hasOwnProperty.call(data, 'name') ||\n !Object.prototype.hasOwnProperty.call(data, 'payload')\n ) {\n console.error('Received malformed data: ', data);\n return;\n }\n\n switch (data.name) {\n case 'samplingRate':\n this.ac.setSamplingRates(data.payload);\n break;\n case 'sampleSize':\n this.ac.setSampleSize(data.payload);\n break;\n case 'deviceType':\n this.ac.setDeviceType(data.payload);\n break;\n case 'deviceName':\n this.ac.setDeviceName(data.payload);\n break;\n case 'deviceInfo':\n this.ac.setDeviceInfo(data.payload);\n console.log('Received device info from listener: ', data.payload);\n break;\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.UnsupportedDeviceError.name:\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.MissingSpeakerIdError.name:\n throw data.payload;\n break;\n default:\n break;\n }\n };\n\n /**\n * Called when the peer connection is #ready.\n *\n * @private\n * @example\n */\n #ready = () => {\n // Perform callback with data\n this.conn.on('data', this.#onIncomingData);\n this.conn.on('close', () => {\n console.log('Connection reset<br>Awaiting connection...');\n this.conn = null;\n });\n };\n\n /** .\n * .\n * .\n * Debug method for downloading the recorded audio\n *\n * @public\n * @example\n */\n downloadData = () => {\n this.ac.downloadData();\n };\n}\n\n/* \nReferenced links:\nhttps://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\nhttps://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]\n*/\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Speaker);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/speaker.js?");
|
|
810
|
+
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 _dist_example_i18n__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../dist/example/i18n */ \"./dist/example/i18n.js\");\n\n\n\n\n\n\n\n/**\n * @class Handles the speaker's side of the connection. Responsible for initiating the connection,\n * rendering the QRCode, and answering the call.\n * @augments AudioPeer\n */\nclass Speaker extends _audioPeer__WEBPACK_IMPORTED_MODULE_1__[\"default\"] {\n /**\n * Takes the url of the current site and a target element where html elements will be appended.\n *\n * @param params - See type definition for initParameters.\n * @param Calibrator - An instance of the AudioCalibrator class, should not use AudioCalibrator directly, instead use an extended class available in /tasks/.\n * @param CalibratorInstance\n * @example\n */\n constructor(params, CalibratorInstance) {\n super(params);\n this.language = params?.language ?? 'en-US';\n this.siteUrl += '/listener?';\n this.ac = CalibratorInstance;\n this.result = null;\n this.debug = params?.debug ?? false;\n this.isSmartPhone = params?.isSmartPhone ?? false;\n this.calibrateSoundHz = params?.calibrateSoundHz ?? 48000;\n this.calibrateSoundSamplingDesiredBits = params?.calibrateSoundSamplingDesiredBits ?? 24;\n this.instructionDisplayId = params?.instructionDisplayId ?? '';\n this.soundSubtitleId = params?.soundSubtitleId ?? '';\n this.timeToCalibrateDisplay = params?.timeToCalibrateId ?? '';\n this.soundMessageId = params?.soundMessageId ?? '';\n this.titleDisplayId = params?.titleDisplayId ?? '';\n this.timeToCalibrate = params?.timeToCalibrate ?? 10;\n\n /* Set up callbacks that handle any events related to our peer object. */\n this.peer.on('open', this.#onPeerOpen);\n this.peer.on('connection', this.#onPeerConnection);\n this.peer.on('close', this.onPeerClose);\n this.peer.on('disconnected', this.#onPeerDisconnected);\n this.peer.on('error', this.#onPeerError);\n }\n /**\n * Async factory method that creates the Speaker object, and returns a promise that resolves to the result of the calibration.\n *\n * @param params - The parameters to be passed to the peer object.\n * @param Calibrator - The class that defines the calibration process.\n * @param CalibratorInstance\n * @param timeOut - The amount of time to wait before timing out the connection (in milliseconds).\n * @public\n * @example\n */\n static startCalibration = async (params, CalibratorInstance, timeOut = 180000) => {\n window.speaker = new Speaker(params, CalibratorInstance);\n const {speaker} = window;\n\n // wrap the calibration process in a promise so we can await it\n return new Promise((resolve, reject) => {\n // when a call is received\n speaker.peer.on('call', async call => {\n // Answer the call (one way)\n\n call.answer();\n speaker.#removeUIElems();\n speaker.#showSpinner();\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\n // when we start receiving audio\n call.on('stream', async stream => {\n console.log(stream);\n window.localStream = stream;\n window.localAudio.srcObject = stream;\n window.localAudio.autoplay = false;\n\n // if the sinkSamplingRate is not set sleep\n while (!speaker.ac.sampleRatesSet()) {\n console.log('SinkSamplingRate is undefined, sleeping');\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\n }\n\n if (params.displayUpdate) {\n params.displayUpdate.style.display = '';\n }\n\n // resolve when we have a result\n speaker.result = await speaker.ac.startCalibration(\n stream,\n params.gainValues,\n params.ICalib,\n params.knownIR,\n params.microphoneName,\n params.calibrateSoundCheck,\n params.isSmartPhone,\n params.calibrateSoundBurstDb,\n params.calibrateSoundBurstRepeats,\n params.calibrateSoundBurstSec,\n params.calibrateSoundBurstsWarmup,\n params.calibrateSoundHz,\n params.calibrateSoundIRSec,\n params.calibrateSoundIIRSec,\n params.calibrateSound1000HzPreSec,\n params.calibrateSound1000HzSec,\n params.calibrateSound1000HzPostSec,\n params.calibrateSoundBackgroundSecs,\n params.calibrateSoundSmoothOctaves,\n params.calibrateSoundPowerBinDesiredSec,\n params.calibrateSoundPowerDbSDToleratedDb,\n params.micManufacturer,\n params.micSerialNumber,\n params.micModelNumber,\n params.micModelName,\n params.calibrateMicrophonesBool,\n params.authorEmails,\n params.webAudioDeviceNames,\n params.IDsToSaveInSoundProfileLibrary,\n params.restartButton,\n params.calibrateSoundLimit\n );\n speaker.#removeUIElems();\n resolve(speaker.result);\n });\n // if we do not receive a result within the timeout, reject\n setTimeout(() => {\n reject(\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\n `Calibration failed to produce a result after ${\n timeOut / 1000\n } seconds. Please try again.`\n )\n );\n }, timeOut);\n });\n });\n };\n\n static testIIR = async (params, CalibratorInstance, IIR, timeOut = 180000) => {\n window.speaker = new Speaker(params, CalibratorInstance);\n const {speaker} = window;\n\n // wrap the calibration process in a promise so we can await it\n return new Promise((resolve, reject) => {\n // when a call is received\n speaker.peer.on('call', async call => {\n // Answer the call (one way)\n call.answer();\n speaker.#removeUIElems();\n speaker.#showSpinner();\n speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));\n // when we start receiving audio\n call.on('stream', async stream => {\n window.localStream = stream;\n window.localAudio.srcObject = stream;\n window.localAudio.autoplay = false;\n\n // if the sinkSamplingRate is not set sleep\n while (!speaker.ac.sampleRatesSet()) {\n console.log('SinkSamplingRate is undefined, sleeping');\n await (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sleep)(1);\n }\n // resolve when we have a result\n speaker.result = await speaker.ac.playMLSwithIIR(stream, IIR);\n speaker.#removeUIElems();\n resolve(speaker.result);\n });\n // if we do not receive a result within the timeout, reject\n setTimeout(() => {\n reject(\n new _peerErrors__WEBPACK_IMPORTED_MODULE_3__.CalibrationTimedOutError(\n `Calibration failed to produce a result after ${\n timeOut / 1000\n } seconds. Please try again.`\n )\n );\n }, timeOut);\n });\n });\n };\n\n /**\n * Called after the peer conncection has been opened.\n * Generates a QR code for the connection and displays it.\n *\n * @private\n * @example\n */\n #showQRCode = () => {\n // Get query string, the URL parameters to specify a Listener\n const queryStringParameters = {\n speakerPeerId: this.peer.id,\n isSmartPhone: this.isSmartPhone,\n calibrateSoundHz: this.calibrateSoundHz,\n calibrateSoundSamplingDesiredBits: this.calibrateSoundSamplingDesiredBits,\n lang: this.language,\n };\n const queryString = this.queryStringFromObject(queryStringParameters);\n const uri = this.siteUrl + queryString;\n if (this.isSmartPhone) {\n // Display QR code for the participant to scan\n const qrCanvas = document.createElement('canvas');\n qrCanvas.setAttribute('id', 'qrCanvas');\n console.log(uri);\n qrcode__WEBPACK_IMPORTED_MODULE_0__.toCanvas(qrCanvas, uri, error => {\n if (error) console.error(error);\n });\n const qrImage = new Image(400, 400);\n qrImage.setAttribute('id', 'compatibilityCheckQRImage');\n qrImage.style.zIndex = Infinity;\n qrImage.style.width = 400;\n qrImage.style.height = 400;\n qrImage.style.aspectRatio = 1;\n qrImage.src = qrCanvas.toDataURL();\n qrImage.style.maxHeight = '150px';\n qrImage.style.maxWidth = '150px';\n document.getElementById(this.targetElement).appendChild(qrImage);\n } else {\n // show the link to the user\n // If specified HTML Id is available, show QR code there\n if (document.getElementById(this.targetElement)) {\n // const linkTag = document.createElement('a');\n // linkTag.setAttribute('href', uri);\n // linkTag.innerHTML = 'Click here to start the calibration';\n // linkTag.target = '_blank';\n // document.getElementById(this.targetElement).appendChild(linkTag);\n // document.getElementById(this.targetElement).appendChild(qrCanvas);\n\n const proceedButton = document.createElement('button');\n proceedButton.setAttribute('id', 'calibrationProceedButton');\n proceedButton.setAttribute('class', 'btn btn-success');\n proceedButton.innerHTML = 'Proceed';\n proceedButton.onclick = () => {\n // open the link in a new tab\n window.open(uri, '_blank');\n // remove the button\n document.getElementById('calibrationProceedButton').remove();\n };\n document.getElementById(this.targetElement).appendChild(proceedButton);\n }\n }\n // or just print it to console\n console.log('TEST: Peer reachable at: ', uri);\n };\n\n #showSpinner = () => {\n const spinner = document.createElement('div');\n spinner.className = 'spinner-border ml-auto';\n spinner.role = 'status';\n spinner.ariaHidden = 'true';\n document.getElementById(this.targetElement).appendChild(spinner);\n\n // clear instructionDisplay\n const soundMessage = document.getElementById(this.soundMessageId);\n soundMessage.innerHTML = '';\n soundMessage.style.display = 'none';\n const instructionDisplay = document.getElementById(this.instructionDisplayId);\n const background = document.getElementById('background'); // todo: get background id from params\n const subtitle = document.getElementById(this.soundSubtitleId);\n if (subtitle) {\n subtitle.innerHTML = '';\n }\n if (instructionDisplay) {\n instructionDisplay.innerHTML = '';\n instructionDisplay.style.whiteSpace = 'nowrap';\n instructionDisplay.style.fontWeight = 'bold';\n instructionDisplay.style.width = 'fit-content';\n instructionDisplay.innerHTML = _dist_example_i18n__WEBPACK_IMPORTED_MODULE_4__.phrases.RC_soundRecording[this.language];\n let fontSize = 100;\n instructionDisplay.style.fontSize = fontSize + 'px';\n while (instructionDisplay.scrollWidth > background.scrollWidth * 0.9 && fontSize > 10) {\n fontSize--;\n instructionDisplay.style.fontSize = fontSize + 'px';\n }\n // const p = document.createElement('p');\n // // font size\n // p.style.fontSize = '1.1rem';\n // p.style.fontWeight = 'normal';\n // p.style.paddingTop = '20px';\n // const timeToCalibrateText = phrases.RC_howLongToCalibrate['en-US'];\n // p.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\n // instructionDisplay.appendChild(p);\n }\n\n const timeToCalibrateDisplay = document.getElementById(this.timeToCalibrateDisplay);\n if (timeToCalibrateDisplay) {\n const timeToCalibrateText = _dist_example_i18n__WEBPACK_IMPORTED_MODULE_4__.phrases.RC_howLongToCalibrate[this.language];\n timeToCalibrateDisplay.innerHTML = timeToCalibrateText.replace('111', this.timeToCalibrate);\n timeToCalibrateDisplay.style.fontWeight = 'normal';\n timeToCalibrateDisplay.style.fontSize = '1rem';\n // timeToCalibrateDisplay.style.paddingTop = '20px';\n }\n\n // Update title - titleDisplayId\n const titleDisplay = document.getElementById(this.titleDisplayId);\n if (titleDisplay) {\n // replace 5 with 6\n titleDisplay.innerHTML = this.isSmartPhone\n ? titleDisplay.innerHTML.replace('2', '3')\n : titleDisplay.innerHTML.replace('4', '5');\n }\n };\n\n #removeUIElems = () => {\n const parent = document.getElementById(this.targetElement);\n while (parent.firstChild) {\n parent.firstChild.remove();\n }\n };\n\n /**\n * Called when the peer connection is opened.\n * Saves the peer id and calls the QR code generator.\n *\n * @param peerId - The peer id of the peer connection.\n * @param id\n * @private\n * @example\n */\n #onPeerOpen = id => {\n // Workaround for peer.reconnect deleting previous id\n if (id === null) {\n console.error('Received null id from peer open');\n this.peer.id = this.lastPeerId;\n } else {\n this.lastPeerId = this.peer.id;\n }\n\n if (id !== this.peer.id) {\n console.warn('DEBUG Check you assumption that id === this.peer.id');\n }\n\n this.#showQRCode();\n };\n\n /**\n * Called when the peer connection is established.\n * Enforces a single connection.\n *\n * @param connection - The connection object.\n * @private\n * @example\n */\n #onPeerConnection = connection => {\n // Allow only a single connection\n if (this.conn && this.conn.open) {\n connection.on('open', () => {\n connection.send('Already connected to another client');\n setTimeout(() => {\n connection.close();\n }, 500);\n });\n return;\n }\n\n this.conn = connection;\n console.log('Connected to: ', this.conn.peer);\n this.#ready();\n };\n\n /**\n * Called when the peer connection is closed.\n *\n * @private\n * @example\n */\n onPeerClose = () => {\n this.conn = null;\n console.log('Connection destroyed');\n };\n\n static closeConnection = () => {\n this.conn = null;\n console.log('Connection destroyed');\n };\n\n /**\n * Called when the peer connection is disconnected.\n * Attempts to reconnect.\n *\n * @private\n * @example\n */\n #onPeerDisconnected = () => {\n console.log('Connection lost. Please reconnect');\n\n // Workaround for peer.reconnect deleting previous id\n this.peer.id = this.lastPeerId;\n // eslint-disable-next-line no-underscore-dangle\n this.peer._lastServerId = this.lastPeerId;\n this.peer.reconnect();\n };\n\n /**\n * Called when the peer connection encounters an error.\n *\n * @param error\n * @private\n * @example\n */\n #onPeerError = error => {\n // TODO: check if this function is needed or not\n console.error(error);\n };\n\n /**\n * Called when data is received from the peer connection.\n *\n * @param data\n * @private\n * @example\n */\n #onIncomingData = data => {\n // enforce object type\n if (\n !Object.prototype.hasOwnProperty.call(data, 'name') ||\n !Object.prototype.hasOwnProperty.call(data, 'payload')\n ) {\n console.error('Received malformed data: ', data);\n return;\n }\n\n switch (data.name) {\n case 'samplingRate':\n this.ac.setSamplingRates(data.payload);\n break;\n case 'sampleSize':\n this.ac.setSampleSize(data.payload);\n break;\n case 'deviceType':\n this.ac.setDeviceType(data.payload);\n break;\n case 'deviceName':\n this.ac.setDeviceName(data.payload);\n break;\n case 'deviceInfo':\n this.ac.setDeviceInfo(data.payload);\n console.log('Received device info from listener: ', data.payload);\n break;\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.UnsupportedDeviceError.name:\n case _peerErrors__WEBPACK_IMPORTED_MODULE_3__.MissingSpeakerIdError.name:\n throw data.payload;\n break;\n default:\n break;\n }\n };\n\n /**\n * Called when the peer connection is #ready.\n *\n * @private\n * @example\n */\n #ready = () => {\n // Perform callback with data\n this.conn.on('data', this.#onIncomingData);\n this.conn.on('close', () => {\n console.log('Connection reset<br>Awaiting connection...');\n this.conn = null;\n });\n };\n\n /** .\n * .\n * .\n * Debug method for downloading the recorded audio\n *\n * @public\n * @example\n */\n downloadData = () => {\n this.ac.downloadData();\n };\n}\n\n/* \nReferenced links:\nhttps://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\nhttps://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep [3]\n*/\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Speaker);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/peer-connection/speaker.js?");
|
|
811
811
|
|
|
812
812
|
/***/ }),
|
|
813
813
|
|
|
@@ -840,7 +840,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _aud
|
|
|
840
840
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
841
841
|
|
|
842
842
|
"use strict";
|
|
843
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _myEventEmitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../myEventEmitter */ \"./src/myEventEmitter.js\");\n\n\n/**\n * @class provides a simple interface for recording audio from a microphone\n * using the Media Recorder API.\n */\nclass AudioRecorder extends _myEventEmitter__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n /** @private */\n #mediaRecorder;\n\n /** @private */\n #recordedChunks = [];\n\n /** @private */\n #audioBlob;\n\n /** @private */\n #audioContext;\n\n /** @private */\n #recordedSignals = [];\n\n /**@private */\n #allHzUnfilteredRecordings = [];\n\n /**@private */\n #allBackgroundRecordings = [];\n\n /** @private */\n #allHzFilteredRecordings = [];\n\n /** @private */\n sinkSamplingRate;\n\n /** @private */\n sampleSize;\n\n /** @private */\n #allVolumeRecordings = [];\n\n /**\n * Decode the audio data from the recorded audio blob.\n *\n * @private\n * @example\n */\n #saveRecording = async (mode, checkRec) => {\n const arrayBuffer = await this.#audioBlob.arrayBuffer();\n const audioBuffer = await this.#audioContext.decodeAudioData(arrayBuffer);\n const data = audioBuffer.getChannelData(0);\n const dataArray = Array.from(data);\n\n console.log(`Decoded audio buffer with ${data.length} samples`);\n console.log(`Unfiltered recording should be of length: ${data.length}`);\n if (checkRec == 'loudest') {\n const uniqueSet = new Set(dataArray);\n const numberOfUniqueValues = uniqueSet.size;\n const squaredValues = dataArray.map(value => value * value);\n const sum_of_squares = squaredValues.reduce((total, value) => total + value, 0);\n const squared_mean = sum_of_squares / dataArray.length;\n const dbLevel = 20 * Math.log10(Math.sqrt(squared_mean));\n const roundedDbLevel = Math.round(dbLevel * 10) / 10;\n console.log(\n 'Loudest 1000-Hz recording: ' +\n roundedDbLevel +\n ' dB with ' +\n numberOfUniqueValues +\n ' unique values.'\n );\n } else if (checkRec == 'allhz') {\n const uniqueSet = new Set(dataArray);\n const numberOfUniqueValues = uniqueSet.size;\n const squaredValues = dataArray.map(value => value * value);\n const sum_of_squares = squaredValues.reduce((total, value) => total + value, 0);\n const squared_mean = sum_of_squares / dataArray.length;\n const dbLevel = 20 * Math.log10(Math.sqrt(squared_mean));\n const roundedDbLevel = Math.round(dbLevel * 10) / 10;\n console.log(\n 'All Hz Recording: ' +\n roundedDbLevel +\n ' dB with ' +\n numberOfUniqueValues +\n ' unique values.'\n );\n }\n if (mode === 'volume'){\n console.log('Saving 1000 Hz Recording to #allVolumeRecordings')\n this.#allVolumeRecordings.push(dataArray);\n }else if (mode ==='unfiltered'){\n console.log('Saving unfiltered all Hz recording to #allHzUnfilteredRecordings')\n this.#allHzUnfilteredRecordings.push(dataArray);\n }else if (mode ==='filtered'){\n console.log('Saving filtered all hz recording to #allHzFilteredRecordings')\n this.#allHzFilteredRecordings.push(dataArray);\n }else if (mode ==='background'){\n console.log('Saving background recording to #allBackgroundRecordings')\n this.#allBackgroundRecordings.push(dataArray);\n }\n\n };\n\n #saveFilteredRecording = async () => {\n const arrayBuffer = await this.#audioBlob.arrayBuffer();\n const audioBuffer = await this.#audioContext.decodeAudioData(arrayBuffer);\n const data = audioBuffer.getChannelData(0);\n\n console.log(`Decoded audio buffer with ${data.length} samples`);\n console.log(`Filtered recording should be of length: ${data.length}`);\n this.#allHzFilteredRecordings.push(Array.from(data));\n };\n\n /**\n * Event listener triggered when data is available in the media recorder.\n *\n * @private\n * @param e - The event object.\n * @example\n */\n #onRecorderDataAvailable = e => {\n if (e.data && e.data.size > 0) this.#recordedChunks.push(e.data);\n };\n\n /**\n * Method to create a media recorder object and set up event listeners.\n *\n * @private\n * @param stream - The stream of audio from the Listener.\n * @example\n */\n #setMediaRecorder = stream => {\n // Create a new MediaRecorder object\n this.#mediaRecorder = new MediaRecorder(stream);\n\n // Add event listeners\n this.#mediaRecorder.ondataavailable = e => this.#onRecorderDataAvailable(e);\n };\n\n #setAudioContext = () => {\n this.#audioContext = new (window.AudioContext ||\n window.webkitAudioContext ||\n window.audioContext)({\n sampleRate: this.sinkSamplingRate,\n sampleSize: this.sampleSize,\n //sampleRate: 96000\n });\n };\n\n /**\n * Public method to start the recording process.\n *\n * @param stream - The stream of audio from the Listener.\n * @example\n */\n startRecording = async stream => {\n try {\n // Create a fresh audio context\n this.#setAudioContext();\n // Set up media recorder if needed\n if (!this.#mediaRecorder) this.#setMediaRecorder(stream);\n // clear recorded chunks\n this.#recordedChunks = [];\n // start recording\n this.#mediaRecorder.start();\n } catch (error) {\n console.error('Error in startRecording:', error);\n // Handle the error as needed, e.g., throw it or perform error-specific actions\n }\n };\n\n /**\n * Method to stop the recording process.\n *\n * @public\n * @example\n */\n stopRecording = async (mode, checkRec) => {\n try {\n // Stop the media recorder, and wait for the data to be available\n await new Promise(resolve => {\n this.#mediaRecorder.onstop = () => {\n // when the stop event is triggered, resolve the promise\n this.#audioBlob = new Blob(this.#recordedChunks, {\n type: 'audio/wav; codecs=opus',\n });\n resolve(this.#audioBlob);\n };\n // call stop\n this.#mediaRecorder.stop();\n });\n // Now that we have data, save it\n await this.#saveRecording(mode, checkRec);\n } catch (error) {\n console.error('Error in stopRecording:', error);\n // Handle the error as needed, e.g., throw it or perform error-specific actions\n }\n };\n\n /** .\n * .\n * .\n * Public method to get the last recorded audio signal\n *\n * @returns\n * @example\n */\n getLastRecordedSignal = () => this.#recordedSignals[this.#recordedSignals.length - 1];\n\n /** .\n * .\n * .\n * Public method to get the last 1000hz recorded audio signal\n *\n * @returns\n * @example\n */\n getLastVolumeRecordedSignal = () => this.#allVolumeRecordings[this.#allVolumeRecordings.length - 1];\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n getAllRecordedSignals = () => this.#recordedSignals;\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n getAllVolumeRecordedSignals = () => this.#allVolumeRecordings;\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n getAllFilteredRecordedSignals = () => this.#allHzFilteredRecordings;\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n clearAllFilteredRecordedSignals = () => this.#allHzFilteredRecordings = [];\n\n /** .\n * .\n * .\n * Public method to clear last the recorded audio signals\n *\n * @returns\n * @example\n */\n clearLastFilteredRecordedSignals = () => this.#allHzFilteredRecordings.pop();\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals for psd\n *\n * @returns\n * @example\n */\n getAllUnfilteredRecordedSignals = () => this.#allHzUnfilteredRecordings;\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n clearLastUnfilteredRecordedSignals = () => this.#allHzUnfilteredRecordings.pop();\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals for psd\n *\n * @returns\n * @example\n */\n getAllBackgroundRecordings = () => this.#allBackgroundRecordings;\n\n /** .\n * .\n * .\n * Public method to set the sampling rate used by the capture device\n *\n * @param {Number} sinkSamplingRate - The sampling rate of the capture device\n * @example\n */\n setSinkSamplingRate = sinkSamplingRate => {\n this.sinkSamplingRate = sinkSamplingRate;\n };\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (AudioRecorder);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/tasks/audioRecorder.js?");
|
|
843
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _myEventEmitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../myEventEmitter */ \"./src/myEventEmitter.js\");\n\n\n/**\n * @class provides a simple interface for recording audio from a microphone\n * using the Media Recorder API.\n */\nclass AudioRecorder extends _myEventEmitter__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n /** @private */\n #mediaRecorder;\n\n /** @private */\n #recordedChunks = [];\n\n /** @private */\n #audioBlob;\n\n /** @private */\n #audioContext;\n\n /** @private */\n #recordedSignals = [];\n\n /**@private */\n #allHzUnfilteredRecordings = [];\n\n /**@private */\n #allBackgroundRecordings = [];\n\n /** @private */\n #allHzFilteredRecordings = [];\n\n /** @private */\n sinkSamplingRate;\n\n /** @private */\n sampleSize;\n\n /** @private */\n #allVolumeRecordings = [];\n\n /**\n * Decode the audio data from the recorded audio blob.\n *\n * @private\n * @example\n */\n #saveRecording = async (mode, checkRec) => {\n const arrayBuffer = await this.#audioBlob.arrayBuffer();\n const audioBuffer = await this.#audioContext.decodeAudioData(arrayBuffer);\n const data = audioBuffer.getChannelData(0);\n const dataArray = Array.from(data);\n\n console.log(`Decoded audio buffer with ${data.length} samples`);\n console.log(`Unfiltered recording should be of length: ${data.length}`);\n if (checkRec == 'loudest') {\n const uniqueSet = new Set(dataArray);\n const numberOfUniqueValues = uniqueSet.size;\n const squaredValues = dataArray.map(value => value * value);\n const sum_of_squares = squaredValues.reduce((total, value) => total + value, 0);\n const squared_mean = sum_of_squares / dataArray.length;\n const dbLevel = 20 * Math.log10(Math.sqrt(squared_mean));\n const roundedDbLevel = Math.round(dbLevel * 10) / 10;\n console.log(\n 'Loudest 1000-Hz recording: ' +\n roundedDbLevel +\n ' dB with ' +\n numberOfUniqueValues +\n ' unique values.'\n );\n } else if (checkRec == 'allhz') {\n const uniqueSet = new Set(dataArray);\n const numberOfUniqueValues = uniqueSet.size;\n const squaredValues = dataArray.map(value => value * value);\n const sum_of_squares = squaredValues.reduce((total, value) => total + value, 0);\n const squared_mean = sum_of_squares / dataArray.length;\n const dbLevel = 20 * Math.log10(Math.sqrt(squared_mean));\n const roundedDbLevel = Math.round(dbLevel * 10) / 10;\n console.log(\n 'All Hz Recording: ' +\n roundedDbLevel +\n ' dB with ' +\n numberOfUniqueValues +\n ' unique values.'\n );\n }\n if (mode === 'volume'){\n console.log('Saving 1000 Hz Recording to #allVolumeRecordings')\n this.#allVolumeRecordings.push(dataArray);\n }else if (mode ==='unfiltered'){\n console.log('Saving unfiltered all Hz recording to #allHzUnfilteredRecordings')\n this.#allHzUnfilteredRecordings.push(dataArray);\n }else if (mode ==='filtered'){\n console.log('Saving filtered all hz recording to #allHzFilteredRecordings')\n this.#allHzFilteredRecordings.push(dataArray);\n }else if (mode ==='background'){\n console.log('Saving background recording to #allBackgroundRecordings')\n this.#allBackgroundRecordings.push(dataArray);\n }\n\n };\n\n #saveFilteredRecording = async () => {\n const arrayBuffer = await this.#audioBlob.arrayBuffer();\n const audioBuffer = await this.#audioContext.decodeAudioData(arrayBuffer);\n const data = audioBuffer.getChannelData(0);\n\n console.log(`Decoded audio buffer with ${data.length} samples`);\n console.log(`Filtered recording should be of length: ${data.length}`);\n this.#allHzFilteredRecordings.push(Array.from(data));\n };\n\n /**\n * Event listener triggered when data is available in the media recorder.\n *\n * @private\n * @param e - The event object.\n * @example\n */\n #onRecorderDataAvailable = e => {\n if (e.data && e.data.size > 0) this.#recordedChunks.push(e.data);\n };\n\n /**\n * Method to create a media recorder object and set up event listeners.\n *\n * @private\n * @param stream - The stream of audio from the Listener.\n * @example\n */\n #setMediaRecorder = stream => {\n // Create a new MediaRecorder object\n this.#mediaRecorder = new MediaRecorder(stream);\n\n // Add event listeners\n this.#mediaRecorder.ondataavailable = e => this.#onRecorderDataAvailable(e);\n };\n\n #setAudioContext = () => {\n this.#audioContext = new (window.AudioContext ||\n window.webkitAudioContext ||\n window.audioContext)({\n sampleRate: this.sinkSamplingRate,\n sampleSize: this.sampleSize,\n //sampleRate: 96000\n });\n };\n\n /**\n * Public method to start the recording process.\n *\n * @param stream - The stream of audio from the Listener.\n * @example\n */\n startRecording = async stream => {\n try {\n // Create a fresh audio context\n this.#setAudioContext();\n // Set up media recorder if needed\n if (!this.#mediaRecorder) this.#setMediaRecorder(stream);\n // clear recorded chunks\n this.#recordedChunks = [];\n // start recording\n this.#mediaRecorder.start();\n } catch (error) {\n console.error('Error in startRecording:', error);\n // Handle the error as needed, e.g., throw it or perform error-specific actions\n }\n };\n\n /**\n * Method to stop the recording process.\n *\n * @public\n * @example\n */\n stopRecording = async (mode, checkRec) => {\n try {\n // Stop the media recorder, and wait for the data to be available\n await new Promise(resolve => {\n this.#mediaRecorder.onstop = () => {\n // when the stop event is triggered, resolve the promise\n this.#audioBlob = new Blob(this.#recordedChunks, {\n type: 'audio/wav; codecs=opus',\n });\n resolve(this.#audioBlob);\n };\n // call stop\n this.#mediaRecorder.stop();\n });\n // Now that we have data, save it\n await this.#saveRecording(mode, checkRec);\n } catch (error) {\n console.error('Error in stopRecording:', error);\n // Handle the error as needed, e.g., throw it or perform error-specific actions\n }\n };\n\n /** .\n * .\n * .\n * Public method to get the last recorded audio signal\n *\n * @returns\n * @example\n */\n getLastRecordedSignal = () => this.#recordedSignals[this.#recordedSignals.length - 1];\n\n /** .\n * .\n * .\n * Public method to get the last 1000hz recorded audio signal\n *\n * @returns\n * @example\n */\n getLastVolumeRecordedSignal = () => Array.from(this.#allVolumeRecordings[this.#allVolumeRecordings.length - 1]);\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n getAllRecordedSignals = () => this.#recordedSignals;\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n getAllVolumeRecordedSignals = () => this.#allVolumeRecordings;\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n getAllFilteredRecordedSignals = () => this.#allHzFilteredRecordings;\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n clearAllFilteredRecordedSignals = () => this.#allHzFilteredRecordings = [];\n\n /** .\n * .\n * .\n * Public method to clear last the recorded audio signals\n *\n * @returns\n * @example\n */\n clearLastFilteredRecordedSignals = () => this.#allHzFilteredRecordings.pop();\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals for psd\n *\n * @returns\n * @example\n */\n getAllUnfilteredRecordedSignals = () => this.#allHzUnfilteredRecordings;\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals\n *\n * @returns\n * @example\n */\n clearLastUnfilteredRecordedSignals = () => this.#allHzUnfilteredRecordings.pop();\n\n /** .\n * .\n * .\n * Public method to get all the recorded audio signals for psd\n *\n * @returns\n * @example\n */\n getAllBackgroundRecordings = () => this.#allBackgroundRecordings;\n\n /** .\n * .\n * .\n * Public method to set the sampling rate used by the capture device\n *\n * @param {Number} sinkSamplingRate - The sampling rate of the capture device\n * @example\n */\n setSinkSamplingRate = sinkSamplingRate => {\n this.sinkSamplingRate = sinkSamplingRate;\n };\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (AudioRecorder);\n\n\n//# sourceURL=webpack://speakerCalibrator/./src/tasks/audioRecorder.js?");
|
|
844
844
|
|
|
845
845
|
/***/ }),
|
|
846
846
|
|
package/package.json
CHANGED
|
@@ -285,28 +285,21 @@ class Listener extends AudioPeer {
|
|
|
285
285
|
return;
|
|
286
286
|
}
|
|
287
287
|
|
|
288
|
-
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
|
289
288
|
navigator.mediaDevices
|
|
290
289
|
.getUserMedia({
|
|
291
290
|
audio: this.getMediaDevicesAudioContraints(),
|
|
292
291
|
video: false,
|
|
293
292
|
})
|
|
294
293
|
.then(stream => {
|
|
295
|
-
const sourceNode = audioContext.createMediaStreamSource(stream);
|
|
296
|
-
const sampleRate = sourceNode.context.sampleRate;
|
|
297
|
-
console.log(sampleRate);
|
|
298
|
-
const audioBuffer = audioContext.createBuffer(1, 1, sampleRate);
|
|
299
|
-
const sampleSizeInBits = audioBuffer.getChannelData(0).BYTES_PER_ELEMENT * 8;
|
|
300
|
-
console.log(sampleSizeInBits);
|
|
301
|
-
audioContext.close();
|
|
302
294
|
this.applyHQTrackConstraints(stream)
|
|
303
295
|
.then(settings => {
|
|
296
|
+
console.log(settings);
|
|
304
297
|
this.sendSamplingRate(sampleRate);
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
this.sendSampleSize(
|
|
298
|
+
let sampleSize = settings.sampleSize;
|
|
299
|
+
if (!sampleSize){
|
|
300
|
+
sampleSize = this.calibrateSoundSamplingDesiredBits;
|
|
301
|
+
}
|
|
302
|
+
this.sendSampleSize(sampleSize);
|
|
310
303
|
this.peer.call(this.speakerPeerId, stream); // one-way call
|
|
311
304
|
this.displayUpdate('Listener - openAudioStream');
|
|
312
305
|
})
|
|
@@ -73,6 +73,7 @@ class Speaker extends AudioPeer {
|
|
|
73
73
|
speaker.ac.createLocalAudio(document.getElementById(speaker.targetElement));
|
|
74
74
|
// when we start receiving audio
|
|
75
75
|
call.on('stream', async stream => {
|
|
76
|
+
console.log(stream);
|
|
76
77
|
window.localStream = stream;
|
|
77
78
|
window.localAudio.srcObject = stream;
|
|
78
79
|
window.localAudio.autoplay = false;
|
|
@@ -213,7 +213,7 @@ class AudioRecorder extends MyEventEmitter {
|
|
|
213
213
|
* @returns
|
|
214
214
|
* @example
|
|
215
215
|
*/
|
|
216
|
-
getLastVolumeRecordedSignal = () => this.#allVolumeRecordings[this.#allVolumeRecordings.length - 1];
|
|
216
|
+
getLastVolumeRecordedSignal = () => Array.from(this.#allVolumeRecordings[this.#allVolumeRecordings.length - 1]);
|
|
217
217
|
|
|
218
218
|
/** .
|
|
219
219
|
* .
|