@siteed/expo-audio-stream 1.0.1 → 1.0.3

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.
Files changed (142) hide show
  1. package/.size-limit.json +6 -0
  2. package/README.md +6 -6
  3. package/android/build.gradle +5 -0
  4. package/android/src/main/java/net/siteed/audiostream/AudioAnalysisData.kt +120 -0
  5. package/android/src/main/java/net/siteed/audiostream/AudioFileHandler.kt +34 -4
  6. package/android/src/main/java/net/siteed/audiostream/AudioProcessor.kt +635 -0
  7. package/android/src/main/java/net/siteed/audiostream/AudioRecorderManager.kt +194 -79
  8. package/android/src/main/java/net/siteed/audiostream/Constants.kt +1 -0
  9. package/android/src/main/java/net/siteed/audiostream/ExpoAudioStreamModule.kt +48 -2
  10. package/android/src/main/java/net/siteed/audiostream/FFT.kt +44 -0
  11. package/android/src/main/java/net/siteed/audiostream/Features.kt +56 -0
  12. package/android/src/main/java/net/siteed/audiostream/RecordingConfig.kt +12 -0
  13. package/android/src/main/test/java/net/siteed/audiostream/AudioProcessorTest.kt +56 -0
  14. package/app.plugin.js +1 -1
  15. package/build/AudioAnalysis/AudioAnalysis.types.d.ts +76 -0
  16. package/build/AudioAnalysis/AudioAnalysis.types.d.ts.map +1 -0
  17. package/build/AudioAnalysis/AudioAnalysis.types.js +3 -0
  18. package/build/AudioAnalysis/AudioAnalysis.types.js.map +1 -0
  19. package/build/AudioAnalysis/extractAudioAnalysis.d.ts +4 -0
  20. package/build/AudioAnalysis/extractAudioAnalysis.d.ts.map +1 -0
  21. package/build/AudioAnalysis/extractAudioAnalysis.js +101 -0
  22. package/build/AudioAnalysis/extractAudioAnalysis.js.map +1 -0
  23. package/build/AudioAnalysis/extractWaveform.d.ts +8 -0
  24. package/build/AudioAnalysis/extractWaveform.d.ts.map +1 -0
  25. package/build/AudioAnalysis/extractWaveform.js +14 -0
  26. package/build/AudioAnalysis/extractWaveform.js.map +1 -0
  27. package/build/AudioRecorder.provider.d.ts +14 -1
  28. package/build/AudioRecorder.provider.d.ts.map +1 -1
  29. package/build/AudioRecorder.provider.js +18 -5
  30. package/build/AudioRecorder.provider.js.map +1 -1
  31. package/build/ExpoAudioStream.native.d.ts +3 -0
  32. package/build/ExpoAudioStream.native.d.ts.map +1 -0
  33. package/build/ExpoAudioStream.native.js +6 -0
  34. package/build/ExpoAudioStream.native.js.map +1 -0
  35. package/build/ExpoAudioStream.types.d.ts +35 -20
  36. package/build/ExpoAudioStream.types.d.ts.map +1 -1
  37. package/build/ExpoAudioStream.types.js.map +1 -1
  38. package/build/ExpoAudioStream.web.d.ts +42 -0
  39. package/build/ExpoAudioStream.web.d.ts.map +1 -0
  40. package/build/ExpoAudioStream.web.js +185 -0
  41. package/build/ExpoAudioStream.web.js.map +1 -0
  42. package/build/ExpoAudioStreamModule.d.ts +2 -2
  43. package/build/ExpoAudioStreamModule.d.ts.map +1 -1
  44. package/build/ExpoAudioStreamModule.js +16 -3
  45. package/build/ExpoAudioStreamModule.js.map +1 -1
  46. package/build/WebRecorder.web.d.ts +51 -0
  47. package/build/WebRecorder.web.d.ts.map +1 -0
  48. package/build/WebRecorder.web.js +288 -0
  49. package/build/WebRecorder.web.js.map +1 -0
  50. package/build/constants.d.ts +11 -0
  51. package/build/constants.d.ts.map +1 -0
  52. package/build/constants.js +14 -0
  53. package/build/constants.js.map +1 -0
  54. package/build/events.d.ts +6 -0
  55. package/build/events.d.ts.map +1 -0
  56. package/build/events.js +15 -0
  57. package/build/events.js.map +1 -0
  58. package/build/index.d.ts +8 -7
  59. package/build/index.d.ts.map +1 -1
  60. package/build/index.js +7 -14
  61. package/build/index.js.map +1 -1
  62. package/build/logger.d.ts +9 -0
  63. package/build/logger.d.ts.map +1 -0
  64. package/build/logger.js +17 -0
  65. package/build/logger.js.map +1 -0
  66. package/build/useAudioRecorder.d.ts +37 -0
  67. package/build/useAudioRecorder.d.ts.map +1 -0
  68. package/build/useAudioRecorder.js +271 -0
  69. package/build/useAudioRecorder.js.map +1 -0
  70. package/build/utils/convertPCMToFloat32.d.ts +11 -0
  71. package/build/utils/convertPCMToFloat32.d.ts.map +1 -0
  72. package/build/utils/convertPCMToFloat32.js +41 -0
  73. package/build/utils/convertPCMToFloat32.js.map +1 -0
  74. package/build/utils/encodingToBitDepth.d.ts +5 -0
  75. package/build/utils/encodingToBitDepth.d.ts.map +1 -0
  76. package/build/utils/encodingToBitDepth.js +13 -0
  77. package/build/utils/encodingToBitDepth.js.map +1 -0
  78. package/build/utils/getWavFileInfo.d.ts +25 -0
  79. package/build/utils/getWavFileInfo.d.ts.map +1 -0
  80. package/build/utils/getWavFileInfo.js +89 -0
  81. package/build/utils/getWavFileInfo.js.map +1 -0
  82. package/build/utils/writeWavHeader.d.ts +9 -0
  83. package/build/utils/writeWavHeader.d.ts.map +1 -0
  84. package/build/utils/writeWavHeader.js +41 -0
  85. package/build/utils/writeWavHeader.js.map +1 -0
  86. package/build/workers/InlineFeaturesExtractor.web.d.ts +2 -0
  87. package/build/workers/InlineFeaturesExtractor.web.d.ts.map +1 -0
  88. package/build/workers/InlineFeaturesExtractor.web.js +303 -0
  89. package/build/workers/InlineFeaturesExtractor.web.js.map +1 -0
  90. package/build/workers/inlineAudioWebWorker.web.d.ts +2 -0
  91. package/build/workers/inlineAudioWebWorker.web.d.ts.map +1 -0
  92. package/build/workers/inlineAudioWebWorker.web.js +243 -0
  93. package/build/workers/inlineAudioWebWorker.web.js.map +1 -0
  94. package/expo-module.config.json +13 -4
  95. package/ios/AudioAnalysisData.swift +39 -0
  96. package/ios/AudioProcessingHelpers.swift +59 -0
  97. package/ios/AudioProcessor.swift +317 -0
  98. package/ios/AudioStreamError.swift +7 -0
  99. package/ios/AudioStreamManager.swift +243 -54
  100. package/ios/AudioStreamManagerDelegate.swift +4 -0
  101. package/ios/DataPoint.swift +41 -0
  102. package/ios/ExpoAudioStreamModule.swift +198 -6
  103. package/ios/Features.swift +44 -0
  104. package/ios/RecordingResult.swift +19 -0
  105. package/ios/RecordingSettings.swift +13 -0
  106. package/ios/WaveformExtractor.swift +105 -0
  107. package/package.json +13 -12
  108. package/plugin/tsconfig.json +13 -8
  109. package/publish.sh +8 -0
  110. package/src/AudioAnalysis/AudioAnalysis.types.ts +85 -0
  111. package/src/AudioAnalysis/extractAudioAnalysis.ts +136 -0
  112. package/src/AudioAnalysis/extractWaveform.ts +25 -0
  113. package/src/AudioRecorder.provider.tsx +36 -8
  114. package/src/ExpoAudioStream.native.ts +6 -0
  115. package/src/ExpoAudioStream.types.ts +50 -25
  116. package/src/ExpoAudioStream.web.ts +229 -0
  117. package/src/ExpoAudioStreamModule.ts +22 -3
  118. package/src/WebRecorder.web.ts +416 -0
  119. package/src/constants.ts +18 -0
  120. package/src/events.ts +25 -0
  121. package/src/index.ts +14 -29
  122. package/src/logger.ts +26 -0
  123. package/src/useAudioRecorder.tsx +415 -0
  124. package/src/utils/convertPCMToFloat32.ts +48 -0
  125. package/src/utils/encodingToBitDepth.ts +18 -0
  126. package/src/utils/getWavFileInfo.ts +125 -0
  127. package/src/utils/writeWavHeader.ts +56 -0
  128. package/src/workers/InlineFeaturesExtractor.web.tsx +302 -0
  129. package/src/workers/inlineAudioWebWorker.web.tsx +242 -0
  130. package/build/ExpoAudioStreamModule.web.d.ts +0 -37
  131. package/build/ExpoAudioStreamModule.web.d.ts.map +0 -1
  132. package/build/ExpoAudioStreamModule.web.js +0 -156
  133. package/build/ExpoAudioStreamModule.web.js.map +0 -1
  134. package/build/useAudioRecording.d.ts +0 -23
  135. package/build/useAudioRecording.d.ts.map +0 -1
  136. package/build/useAudioRecording.js +0 -189
  137. package/build/useAudioRecording.js.map +0 -1
  138. package/docs/demo.gif +0 -0
  139. package/release-it.js +0 -18
  140. package/src/ExpoAudioStreamModule.web.ts +0 -181
  141. package/src/useAudioRecording.ts +0 -268
  142. package/yarn-error.log +0 -7793
@@ -0,0 +1,302 @@
1
+ export const InlineFeaturesExtractor = `
2
+
3
+ // Unique ID counter
4
+ let uniqueIdCounter = 0;
5
+
6
+ self.onmessage = function (event) {
7
+ const {
8
+ channelData, // this is only the newly recorded data when live recording.
9
+ sampleRate,
10
+ pointsPerSecond,
11
+ algorithm,
12
+ bitDepth,
13
+ fullAudioDurationMs,
14
+ numberOfChannels,
15
+ features: _features,
16
+ } = event.data;
17
+
18
+ console.log("[AudioFeaturesExtractor] Worker received message", event.data);
19
+ const features = _features || {};
20
+
21
+ const SILENCE_THRESHOLD = 0.01;
22
+ const MIN_SILENCE_DURATION = 1.5 * sampleRate; // 1.5 seconds of silence
23
+ const SPEECH_INERTIA_DURATION = 0.1 * sampleRate; // Speech inertia duration in samples
24
+ const RMS_THRESHOLD = 0.01;
25
+ const ZCR_THRESHOLD = 0.1;
26
+
27
+ // Placeholder functions for feature extraction
28
+ const extractMFCC = (segmentData, sampleRate) => {
29
+ // Implement MFCC extraction logic here
30
+ return [];
31
+ };
32
+
33
+ const extractSpectralCentroid = (segmentData, sampleRate) => {
34
+ const magnitudeSpectrum = segmentData.map((v) => v * v);
35
+ const sum = magnitudeSpectrum.reduce((a, b) => a + b, 0);
36
+ if (sum === 0) return 0;
37
+
38
+ const weightedSum = magnitudeSpectrum.reduce(
39
+ (acc, value, index) => acc + index * value,
40
+ 0,
41
+ );
42
+ return ((weightedSum / sum) * (sampleRate / 2)) / magnitudeSpectrum.length;
43
+ };
44
+
45
+ const extractSpectralFlatness = (segmentData) => {
46
+ const magnitudeSpectrum = segmentData.map((v) => Math.abs(v));
47
+ const geometricMean = Math.exp(
48
+ magnitudeSpectrum
49
+ .map((v) => Math.log(v + Number.MIN_VALUE))
50
+ .reduce((a, b) => a + b) / magnitudeSpectrum.length,
51
+ );
52
+ const arithmeticMean =
53
+ magnitudeSpectrum.reduce((a, b) => a + b) / magnitudeSpectrum.length;
54
+ return arithmeticMean === 0 ? 0 : geometricMean / arithmeticMean;
55
+ };
56
+
57
+ const extractSpectralRollOff = (segmentData, sampleRate) => {
58
+ const magnitudeSpectrum = segmentData.map((v) => Math.abs(v));
59
+ const totalEnergy = magnitudeSpectrum.reduce((a, b) => a + b, 0);
60
+ const rollOffThreshold = totalEnergy * 0.85;
61
+ let cumulativeEnergy = 0;
62
+
63
+ for (let i = 0; i < magnitudeSpectrum.length; i++) {
64
+ cumulativeEnergy += magnitudeSpectrum[i];
65
+ if (cumulativeEnergy >= rollOffThreshold) {
66
+ return (i / magnitudeSpectrum.length) * (sampleRate / 2);
67
+ }
68
+ }
69
+
70
+ return 0;
71
+ };
72
+
73
+ const extractSpectralBandwidth = (segmentData, sampleRate) => {
74
+ const centroid = extractSpectralCentroid(segmentData, sampleRate);
75
+ const magnitudeSpectrum = segmentData.map((v) => Math.abs(v));
76
+ const sum = magnitudeSpectrum.reduce((a, b) => a + b, 0);
77
+ if (sum === 0) return 0;
78
+
79
+ const weightedSum = magnitudeSpectrum.reduce(
80
+ (acc, value, index) => acc + value * Math.pow(index - centroid, 2),
81
+ 0,
82
+ );
83
+ return Math.sqrt(weightedSum / sum);
84
+ };
85
+
86
+ const extractChromagram = (segmentData, sampleRate) => {
87
+ return []; // TODO implement
88
+ };
89
+
90
+ const extractHNR = (segmentData) => {
91
+ const frameSize = segmentData.length;
92
+ const autocorrelation = new Float32Array(frameSize);
93
+
94
+ // Compute the autocorrelation of the segment data
95
+ for (let i = 0; i < frameSize; i++) {
96
+ let sum = 0;
97
+ for (let j = 0; j < frameSize - i; j++) {
98
+ sum += segmentData[j] * segmentData[j + i];
99
+ }
100
+ autocorrelation[i] = sum;
101
+ }
102
+
103
+ // Find the maximum autocorrelation value (excluding the zero lag)
104
+ const maxAutocorrelation = Math.max(...autocorrelation.subarray(1));
105
+
106
+ // Compute the HNR
107
+ return autocorrelation[0] !== 0
108
+ ? 10 *
109
+ Math.log10(
110
+ maxAutocorrelation / (autocorrelation[0] - maxAutocorrelation),
111
+ )
112
+ : 0;
113
+ };
114
+
115
+ const extractWaveform = (
116
+ channelData, // Float32Array
117
+ sampleRate, // number
118
+ pointsPerSecond, // number
119
+ algorithm, // string
120
+ ) => {
121
+ const totalSamples = channelData.length;
122
+ const segmentDuration = totalSamples / sampleRate;
123
+ const totalPoints = Math.max(
124
+ Math.ceil(segmentDuration * pointsPerSecond),
125
+ 1,
126
+ );
127
+ const pointInterval = Math.ceil(totalSamples / totalPoints);
128
+ const dataPoints = [];
129
+ let minAmplitude = Infinity;
130
+ let maxAmplitude = -Infinity;
131
+ let silenceStart = null;
132
+ let lastSpeechEnd = -Infinity;
133
+ let isSpeech = false;
134
+
135
+ const expectedPoints = segmentDuration * pointsPerSecond;
136
+ const samplesPerPoint = Math.ceil(channelData.length / expectedPoints);
137
+
138
+ for (let i = 0; i < expectedPoints; i++) {
139
+ const start = i * samplesPerPoint;
140
+ const end = Math.min(start + samplesPerPoint, totalSamples);
141
+
142
+ let sumSquares = 0;
143
+ let zeroCrossings = 0;
144
+ let prevValue = channelData[start];
145
+ let localMinAmplitude = Infinity;
146
+ let localMaxAmplitude = -Infinity;
147
+ let hasNonZeroValue = false;
148
+
149
+ // compute values for the segment
150
+ for (let j = start; j < end; j++) {
151
+ const value = channelData[j];
152
+ sumSquares += value * value;
153
+ if (j > start && value * prevValue < 0) {
154
+ zeroCrossings++;
155
+ }
156
+ prevValue = value;
157
+
158
+ const absValue = Math.abs(value);
159
+ localMinAmplitude = Math.min(localMinAmplitude, absValue);
160
+ localMaxAmplitude = Math.max(localMaxAmplitude, absValue);
161
+
162
+ if (absValue !== 0) {
163
+ hasNonZeroValue = true;
164
+ }
165
+ }
166
+
167
+ // Post-processing checks
168
+ if (!hasNonZeroValue) {
169
+ // All values are zero
170
+ localMinAmplitude = 0;
171
+ localMaxAmplitude = 0;
172
+ }
173
+
174
+ const rms = Math.sqrt(sumSquares / (end - start));
175
+ minAmplitude = Math.min(minAmplitude, rms);
176
+ maxAmplitude = Math.max(maxAmplitude, rms);
177
+
178
+ const energy = sumSquares;
179
+ const zcr = zeroCrossings / (end - start);
180
+
181
+ const silent = rms < SILENCE_THRESHOLD;
182
+ const dB = 20 * Math.log10(rms);
183
+
184
+ if (silent) {
185
+ if (silenceStart === null) {
186
+ silenceStart = start;
187
+ } else if (start - silenceStart > MIN_SILENCE_DURATION) {
188
+ // Silence detected for longer than the threshold, set amplitude to 0
189
+ localMaxAmplitude = 0;
190
+ localMinAmplitude = 0;
191
+ isSpeech = false;
192
+ }
193
+ } else {
194
+ silenceStart = null;
195
+ if (!isSpeech && start - lastSpeechEnd < SPEECH_INERTIA_DURATION) {
196
+ isSpeech = true;
197
+ }
198
+ lastSpeechEnd = end;
199
+ }
200
+
201
+ const activeSpeech =
202
+ (rms > RMS_THRESHOLD && zcr > ZCR_THRESHOLD) ||
203
+ (isSpeech && start - lastSpeechEnd < SPEECH_INERTIA_DURATION);
204
+
205
+ if (activeSpeech) {
206
+ isSpeech = true;
207
+ lastSpeechEnd = end;
208
+ } else {
209
+ isSpeech = false;
210
+ }
211
+
212
+ const bytesPerSample = bitDepth / 8;
213
+ const startPosition = start * bytesPerSample * numberOfChannels; // Calculate start position in bytes
214
+ const endPosition = end * bytesPerSample * numberOfChannels; // Calculate end position in bytes
215
+
216
+ // Compute features
217
+ const segmentData = channelData.slice(start, end);
218
+ const mfcc = features.mfcc ? extractMFCC(segmentData, sampleRate) : [];
219
+ const spectralCentroid = features.spectralCentroid
220
+ ? extractSpectralCentroid(segmentData, sampleRate)
221
+ : 0;
222
+ const spectralFlatness = features.spectralFlatness
223
+ ? extractSpectralFlatness(segmentData)
224
+ : 0;
225
+ const spectralRollOff = features.spectralRollOff
226
+ ? extractSpectralRollOff(segmentData, sampleRate)
227
+ : 0;
228
+ const spectralBandwidth = features.spectralBandwidth
229
+ ? extractSpectralBandwidth(segmentData, sampleRate)
230
+ : 0;
231
+ const chromagram = features.chromagram
232
+ ? extractChromagram(segmentData, sampleRate)
233
+ : [];
234
+ const hnr = features.hnr ? extractHNR(segmentData) : 0;
235
+
236
+ const newData = {
237
+ id: uniqueIdCounter++, // Assign unique ID and increment the counter
238
+ amplitude: algorithm === "peak" ? localMaxAmplitude : rms,
239
+ activeSpeech,
240
+ dB,
241
+ silent,
242
+ features: {
243
+ energy,
244
+ rms,
245
+ minAmplitude: localMinAmplitude,
246
+ maxAmplitude: localMaxAmplitude,
247
+ zcr,
248
+ mfcc: [], // Placeholder for MFCC features
249
+ spectralCentroid, // Computed spectral centroid
250
+ spectralFlatness, // Computed spectral flatness
251
+ spectralRollOff, // Computed spectral roll-off
252
+ spectralBandwidth, // Computed spectral bandwidth
253
+ chromagram, // Computed chromagram
254
+ hnr, // Computed HNR
255
+ },
256
+ startTime: start / sampleRate,
257
+ endTime: end / sampleRate,
258
+ startPosition,
259
+ endPosition,
260
+ samples: end - start,
261
+ speaker: 0, // Assuming speaker detection is to be handled later
262
+ };
263
+
264
+ dataPoints.push(newData);
265
+ }
266
+
267
+ return {
268
+ pointsPerSecond,
269
+ durationMs: fullAudioDurationMs,
270
+ bitDepth,
271
+ samples: totalSamples,
272
+ numberOfChannels,
273
+ sampleRate,
274
+ dataPoints,
275
+ amplitudeRange: {
276
+ min: minAmplitude,
277
+ max: maxAmplitude,
278
+ },
279
+ speakerChanges: [], // Placeholder for future speaker detection logic
280
+ };
281
+ };
282
+
283
+ try {
284
+ const result = extractWaveform(
285
+ channelData,
286
+ sampleRate,
287
+ pointsPerSecond,
288
+ algorithm,
289
+ );
290
+ self.postMessage({
291
+ command: "features",
292
+ result,
293
+ });
294
+ } catch (error) {
295
+ console.error("[AudioFeaturesExtractor] Error in processing", error);
296
+ self.postMessage({ error: error.message });
297
+ } finally {
298
+ // Do not close the worker so it can be re-used for subsequent messages
299
+ // self.close();
300
+ }
301
+ };
302
+ `;
@@ -0,0 +1,242 @@
1
+ export const InlineAudioWebWorker = `
2
+ const DEFAULT_BIT_DEPTH = 32;
3
+ const DEFAULT_SAMPLE_RATE = 44100;
4
+
5
+ class RecorderProcessor extends AudioWorkletProcessor {
6
+ constructor() {
7
+ super();
8
+ this.recordedBuffers = []; // Float32Array
9
+ this.newRecBuffer = []; // Float32Array
10
+ this.resampledBuffer = []; // Float32Array
11
+ this.exportIntervalSamples = 0;
12
+ this.samplesSinceLastExport = 0;
13
+ this.recordSampleRate = DEFAULT_SAMPLE_RATE; // To be overwritten
14
+ this.exportSampleRate = DEFAULT_SAMPLE_RATE; // To be overwritten
15
+ this.recordBitDepth = DEFAULT_BIT_DEPTH; // Default to 32-bit depth
16
+ this.exportBitDepth = DEFAULT_BIT_DEPTH; // To be overwritten
17
+ this.numberOfChannels = 1; // Default to 1 channel (mono)
18
+ this.isRecording = true;
19
+ this.port.onmessage = this.handleMessage.bind(this);
20
+ }
21
+
22
+ handleMessage(event) {
23
+ switch (event.data.command) {
24
+ case "init":
25
+ this.recordSampleRate = event.data.recordSampleRate;
26
+ this.exportSampleRate =
27
+ event.data.exportSampleRate || event.data.recordSampleRate;
28
+ this.exportIntervalSamples =
29
+ this.recordSampleRate * (event.data.interval / 1000);
30
+ if (event.data.numberOfChannels) {
31
+ this.numberOfChannels = event.data.numberOfChannels;
32
+ }
33
+ if (event.data.recordBitDepth) {
34
+ this.recordBitDepth = event.data.recordBitDepth;
35
+ }
36
+ this.exportBitDepth =
37
+ event.data.exportBitDepth || this.recordBitDepth || DEFAULT_BIT_DEPTH;
38
+ break;
39
+ case "stop":
40
+ this.isRecording = false;
41
+ this.getAllRecordedData()
42
+ .then((fullRecordedData) => {
43
+ this.port.postMessage({
44
+ command: "recordedData",
45
+ recordedData: fullRecordedData,
46
+ bitDepth: this.exportBitDepth,
47
+ sampleRate: this.exportSampleRate,
48
+ });
49
+ return fullRecordedData;
50
+ })
51
+ .catch((error) => {
52
+ console.error("Error extracting recorded data:", error);
53
+ });
54
+ break;
55
+ }
56
+ }
57
+
58
+ process(inputs, outputs, parameters) {
59
+ if (!this.isRecording) return true;
60
+ const input = inputs[0];
61
+ if (input.length > 0) {
62
+ const newBuffer = new Float32Array(input[0]);
63
+ this.newRecBuffer.push(newBuffer);
64
+ this.recordedBuffers.push(newBuffer);
65
+ this.samplesSinceLastExport += newBuffer.length;
66
+
67
+ if (this.samplesSinceLastExport >= this.exportIntervalSamples) {
68
+ this.exportNewData();
69
+ this.samplesSinceLastExport = 0;
70
+ }
71
+ }
72
+ return true;
73
+ }
74
+
75
+ mergeBuffers(bufferArray, recLength) {
76
+ const result = new Float32Array(recLength);
77
+ let offset = 0;
78
+ for (let i = 0; i < bufferArray.length; i++) {
79
+ result.set(bufferArray[i], offset);
80
+ offset += bufferArray[i].length;
81
+ }
82
+ return result;
83
+ }
84
+
85
+ floatTo16BitPCM(input) {
86
+ const output = new Int16Array(input.length);
87
+ for (let i = 0; i < input.length; i++) {
88
+ const s = Math.max(-1, Math.min(1, input[i]));
89
+ output[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
90
+ }
91
+ console.debug(
92
+ "Float to 16-bit PCM conversion complete. Output byte length:",
93
+ output.byteLength,
94
+ );
95
+ return output;
96
+ }
97
+
98
+ floatTo32BitPCM(input) {
99
+ const output = new Int32Array(input.length);
100
+ for (let i = 0; i < input.length; i++) {
101
+ const s = Math.max(-1, Math.min(1, input[i]));
102
+ output[i] = s < 0 ? s * 0x80000000 : s * 0x7fffffff;
103
+ }
104
+ console.debug(
105
+ "Float to 32-bit PCM conversion complete. Output byte length:",
106
+ output.byteLength,
107
+ );
108
+ return output;
109
+ }
110
+
111
+ resample(samples, targetSampleRate) {
112
+ if (this.recordSampleRate === targetSampleRate) {
113
+ return samples;
114
+ }
115
+ const resampledBuffer = new Float32Array(
116
+ (samples.length * targetSampleRate) / this.recordSampleRate,
117
+ );
118
+ const ratio = this.recordSampleRate / targetSampleRate;
119
+ let offset = 0;
120
+ for (let i = 0; i < resampledBuffer.length; i++) {
121
+ const nextOffset = Math.floor((i + 1) * ratio);
122
+ let accum = 0;
123
+ let count = 0;
124
+ for (let j = offset; j < nextOffset && j < samples.length; j++) {
125
+ accum += samples[j];
126
+ count++;
127
+ }
128
+ resampledBuffer[i] = accum / count;
129
+ offset = nextOffset;
130
+ }
131
+ return resampledBuffer;
132
+ }
133
+
134
+ async resampleBuffer(buffer, targetSampleRate) {
135
+ if (typeof OfflineAudioContext === "undefined") {
136
+ return this.resample(buffer, targetSampleRate);
137
+ }
138
+
139
+ if (this.recordSampleRate === targetSampleRate) {
140
+ return buffer;
141
+ }
142
+ const offlineContext = new OfflineAudioContext(
143
+ this.numberOfChannels,
144
+ buffer.length,
145
+ this.recordSampleRate,
146
+ );
147
+ const sourceBuffer = offlineContext.createBuffer(
148
+ this.numberOfChannels,
149
+ buffer.length,
150
+ this.recordSampleRate,
151
+ );
152
+ sourceBuffer.copyToChannel(buffer, 0);
153
+
154
+ const bufferSource = offlineContext.createBufferSource();
155
+ bufferSource.buffer = sourceBuffer;
156
+ bufferSource.connect(offlineContext.destination);
157
+ bufferSource.start();
158
+
159
+ const renderedBuffer = await offlineContext.startRendering();
160
+
161
+ const resampledBuffer = new Float32Array(renderedBuffer.length);
162
+ renderedBuffer.copyFromChannel(resampledBuffer, 0);
163
+
164
+ return resampledBuffer;
165
+ }
166
+
167
+ async exportNewData() {
168
+ // Calculate the total length of the new recorded buffers
169
+ const length = this.newRecBuffer.reduce(
170
+ (acc, buffer) => acc + buffer.length,
171
+ 0,
172
+ );
173
+
174
+ // Merge all new recorded buffers into a single buffer
175
+ const mergedBuffer = this.mergeBuffers(this.newRecBuffer, length);
176
+
177
+ const resampledBuffer = await this.resampleBuffer(
178
+ mergedBuffer,
179
+ this.exportSampleRate,
180
+ );
181
+
182
+ let finalBuffer = resampledBuffer; // Float32Array
183
+ if (this.recordBitDepth !== this.exportBitDepth) {
184
+ if (this.exportBitDepth === 16) {
185
+ finalBuffer = this.floatTo16BitPCM(resampledBuffer);
186
+ } else if (this.exportBitDepth === 32) {
187
+ finalBuffer = this.floatTo32BitPCM(resampledBuffer);
188
+ }
189
+ }
190
+
191
+ const originalSize = mergedBuffer.byteLength;
192
+ const resampledSize = resampledBuffer.byteLength;
193
+ const finalSize = finalBuffer.byteLength;
194
+
195
+ // Clear the new recorded buffers after they have been processed
196
+ this.newRecBuffer.length = 0;
197
+
198
+ // Post the message to the main thread
199
+ // The first argument is the message data, containing the encoded WAV buffer
200
+ // The second argument is the transfer list, which transfers ownership of the ArrayBuffer
201
+ // to the main thread, avoiding the need to copy the buffer and improving performance
202
+ // this.port.postMessage({ recordedData: encodedWav.buffer, sampleRate: this.recordSampleRate }, [encodedWav.buffer]);
203
+ this.port.postMessage({
204
+ command: "newData",
205
+ recordedData: finalBuffer.buffer,
206
+ sampleRate: this.exportSampleRate,
207
+ bitDepth: this.exportBitDepth,
208
+ });
209
+ }
210
+
211
+ async getAllRecordedData() {
212
+ const length = this.recordedBuffers.reduce(
213
+ (acc, buffer) => acc + buffer.length,
214
+ 0,
215
+ );
216
+ const mergedBuffer = this.mergeBuffers(this.recordedBuffers, length);
217
+ const resampledBuffer = await this.resampleBuffer(
218
+ mergedBuffer,
219
+ this.exportSampleRate,
220
+ );
221
+ // Convert to the desired bit depth if necessary
222
+ let finalBuffer = resampledBuffer;
223
+ if (this.recordBitDepth !== this.exportBitDepth) {
224
+ if (this.exportBitDepth === 16) {
225
+ finalBuffer = this.floatTo16BitPCM(resampledBuffer);
226
+ } else if (this.exportBitDepth === 32) {
227
+ finalBuffer = this.floatTo32BitPCM(resampledBuffer);
228
+ }
229
+ }
230
+
231
+ const originalSize = mergedBuffer.byteLength;
232
+ const resampledSize = resampledBuffer.byteLength;
233
+ const finalSize = finalBuffer.byteLength;
234
+
235
+ this.recordedBuffers.length = 0; // Clear the buffers after extraction
236
+
237
+ return finalBuffer.buffer;
238
+ }
239
+ }
240
+
241
+ registerProcessor("recorder-processor", RecorderProcessor);
242
+ `;
@@ -1,37 +0,0 @@
1
- import { EventEmitter } from "expo-modules-core";
2
- import { AudioStreamResult, RecordingConfig, StartAudioStreamResult } from "./ExpoAudioStream.types";
3
- declare class ExpoAudioStreamWeb extends EventEmitter {
4
- mediaRecorder: MediaRecorder | null;
5
- audioChunks: Blob[];
6
- isRecording: boolean;
7
- isPaused: boolean;
8
- recordingStartTime: number;
9
- pausedTime: number;
10
- currentDurationMs: number;
11
- currentSize: number;
12
- currentInterval: number;
13
- lastEmittedSize: number;
14
- lastEmittedTime: number;
15
- streamUuid: string | null;
16
- constructor();
17
- getMediaStream(): Promise<MediaStream>;
18
- startRecording(options?: RecordingConfig): Promise<StartAudioStreamResult>;
19
- setupRecordingListeners(): void;
20
- emitAudioEvent({ data, position }: {
21
- data: Blob;
22
- position: number;
23
- }): void;
24
- generateUUID(): string;
25
- stopRecording(): Promise<AudioStreamResult | null>;
26
- pauseRecording(): Promise<void>;
27
- status(): {
28
- isRecording: boolean;
29
- isPaused: boolean;
30
- duration: number;
31
- size: number;
32
- interval: number;
33
- };
34
- }
35
- declare const _default: ExpoAudioStreamWeb;
36
- export default _default;
37
- //# sourceMappingURL=ExpoAudioStreamModule.web.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ExpoAudioStreamModule.web.d.ts","sourceRoot":"","sources":["../src/ExpoAudioStreamModule.web.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EAEL,iBAAiB,EACjB,eAAe,EACf,sBAAsB,EACvB,MAAM,yBAAyB,CAAC;AAGjC,cAAM,kBAAmB,SAAQ,YAAY;IAC3C,aAAa,EAAE,aAAa,GAAG,IAAI,CAAC;IACpC,WAAW,EAAE,IAAI,EAAE,CAAC;IACpB,WAAW,EAAE,OAAO,CAAC;IACrB,QAAQ,EAAE,OAAO,CAAC;IAClB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;;IA4BpB,cAAc;IAUd,cAAc,CAAC,OAAO,GAAE,eAAoB;IAwBlD,uBAAuB;IA4BvB,cAAc,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE;IAiBnE,YAAY;IAUN,aAAa,IAAI,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAelD,cAAc;IAcpB,MAAM;;;;;;;CASP;;AAED,wBAAwC"}