@siteed/expo-audio-stream 1.0.2 → 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 (113) hide show
  1. package/.size-limit.json +6 -0
  2. package/build/AudioAnalysis/AudioAnalysis.types.d.ts +76 -0
  3. package/build/AudioAnalysis/AudioAnalysis.types.d.ts.map +1 -0
  4. package/build/AudioAnalysis/AudioAnalysis.types.js +3 -0
  5. package/build/AudioAnalysis/AudioAnalysis.types.js.map +1 -0
  6. package/build/AudioAnalysis/extractAudioAnalysis.d.ts +4 -0
  7. package/build/AudioAnalysis/extractAudioAnalysis.d.ts.map +1 -0
  8. package/build/AudioAnalysis/extractAudioAnalysis.js +101 -0
  9. package/build/AudioAnalysis/extractAudioAnalysis.js.map +1 -0
  10. package/build/AudioAnalysis/extractWaveform.d.ts +8 -0
  11. package/build/AudioAnalysis/extractWaveform.d.ts.map +1 -0
  12. package/build/AudioAnalysis/extractWaveform.js +14 -0
  13. package/build/AudioAnalysis/extractWaveform.js.map +1 -0
  14. package/build/AudioRecorder.provider.d.ts +14 -1
  15. package/build/AudioRecorder.provider.d.ts.map +1 -1
  16. package/build/AudioRecorder.provider.js +17 -4
  17. package/build/AudioRecorder.provider.js.map +1 -1
  18. package/build/ExpoAudioStream.types.d.ts +26 -84
  19. package/build/ExpoAudioStream.types.d.ts.map +1 -1
  20. package/build/ExpoAudioStream.types.js.map +1 -1
  21. package/build/ExpoAudioStream.web.d.ts +6 -5
  22. package/build/ExpoAudioStream.web.d.ts.map +1 -1
  23. package/build/ExpoAudioStream.web.js +9 -8
  24. package/build/ExpoAudioStream.web.js.map +1 -1
  25. package/build/ExpoAudioStreamModule.d.ts.map +1 -1
  26. package/build/ExpoAudioStreamModule.js +5 -1
  27. package/build/ExpoAudioStreamModule.js.map +1 -1
  28. package/build/{WebRecorder.d.ts → WebRecorder.web.d.ts} +7 -3
  29. package/build/WebRecorder.web.d.ts.map +1 -0
  30. package/build/{WebRecorder.js → WebRecorder.web.js} +74 -29
  31. package/build/WebRecorder.web.js.map +1 -0
  32. package/build/constants.d.ts +11 -0
  33. package/build/constants.d.ts.map +1 -0
  34. package/build/constants.js +14 -0
  35. package/build/constants.js.map +1 -0
  36. package/build/events.d.ts +6 -0
  37. package/build/events.d.ts.map +1 -0
  38. package/build/events.js +15 -0
  39. package/build/events.js.map +1 -0
  40. package/build/index.d.ts +8 -16
  41. package/build/index.d.ts.map +1 -1
  42. package/build/index.js +6 -112
  43. package/build/index.js.map +1 -1
  44. package/build/logger.d.ts +9 -0
  45. package/build/logger.d.ts.map +1 -0
  46. package/build/logger.js +17 -0
  47. package/build/logger.js.map +1 -0
  48. package/build/{useAudioRecording.d.ts → useAudioRecorder.d.ts} +6 -7
  49. package/build/useAudioRecorder.d.ts.map +1 -0
  50. package/build/{useAudioRecording.js → useAudioRecorder.js} +69 -65
  51. package/build/useAudioRecorder.js.map +1 -0
  52. package/build/utils/convertPCMToFloat32.d.ts +11 -0
  53. package/build/utils/convertPCMToFloat32.d.ts.map +1 -0
  54. package/build/utils/convertPCMToFloat32.js +41 -0
  55. package/build/utils/convertPCMToFloat32.js.map +1 -0
  56. package/build/utils/encodingToBitDepth.d.ts +5 -0
  57. package/build/utils/encodingToBitDepth.d.ts.map +1 -0
  58. package/build/utils/encodingToBitDepth.js +13 -0
  59. package/build/utils/encodingToBitDepth.js.map +1 -0
  60. package/build/utils/getWavFileInfo.d.ts +25 -0
  61. package/build/utils/getWavFileInfo.d.ts.map +1 -0
  62. package/build/utils/getWavFileInfo.js +89 -0
  63. package/build/utils/getWavFileInfo.js.map +1 -0
  64. package/build/utils/writeWavHeader.d.ts +9 -0
  65. package/build/utils/writeWavHeader.d.ts.map +1 -0
  66. package/build/utils/writeWavHeader.js +41 -0
  67. package/build/utils/writeWavHeader.js.map +1 -0
  68. package/build/workers/InlineFeaturesExtractor.web.d.ts +2 -0
  69. package/build/workers/InlineFeaturesExtractor.web.d.ts.map +1 -0
  70. package/build/workers/InlineFeaturesExtractor.web.js +303 -0
  71. package/build/workers/InlineFeaturesExtractor.web.js.map +1 -0
  72. package/build/workers/inlineAudioWebWorker.web.d.ts +2 -0
  73. package/build/workers/inlineAudioWebWorker.web.d.ts.map +1 -0
  74. package/build/workers/inlineAudioWebWorker.web.js +243 -0
  75. package/build/workers/inlineAudioWebWorker.web.js.map +1 -0
  76. package/ios/AudioStreamManager.swift +39 -2
  77. package/ios/ExpoAudioStreamModule.swift +10 -0
  78. package/package.json +7 -6
  79. package/plugin/tsconfig.json +1 -1
  80. package/publish.sh +0 -0
  81. package/src/AudioAnalysis/AudioAnalysis.types.ts +85 -0
  82. package/src/AudioAnalysis/extractAudioAnalysis.ts +136 -0
  83. package/src/AudioAnalysis/extractWaveform.ts +25 -0
  84. package/src/AudioRecorder.provider.tsx +35 -7
  85. package/src/ExpoAudioStream.types.ts +33 -94
  86. package/src/ExpoAudioStream.web.ts +17 -16
  87. package/src/ExpoAudioStreamModule.ts +6 -1
  88. package/src/{WebRecorder.ts → WebRecorder.web.ts} +85 -33
  89. package/src/constants.ts +18 -0
  90. package/src/events.ts +25 -0
  91. package/src/index.ts +8 -169
  92. package/src/logger.ts +26 -0
  93. package/src/{useAudioRecording.tsx → useAudioRecorder.tsx} +141 -136
  94. package/src/utils/convertPCMToFloat32.ts +48 -0
  95. package/src/utils/encodingToBitDepth.ts +18 -0
  96. package/src/utils/getWavFileInfo.ts +125 -0
  97. package/src/utils/writeWavHeader.ts +56 -0
  98. package/src/workers/InlineFeaturesExtractor.web.tsx +302 -0
  99. package/src/workers/inlineAudioWebWorker.web.tsx +242 -0
  100. package/build/WebRecorder.d.ts.map +0 -1
  101. package/build/WebRecorder.js.map +0 -1
  102. package/build/inlineAudioWebWorker.d.ts +0 -3
  103. package/build/inlineAudioWebWorker.d.ts.map +0 -1
  104. package/build/inlineAudioWebWorker.js +0 -340
  105. package/build/inlineAudioWebWorker.js.map +0 -1
  106. package/build/useAudioRecording.d.ts.map +0 -1
  107. package/build/useAudioRecording.js.map +0 -1
  108. package/build/utils.d.ts +0 -31
  109. package/build/utils.d.ts.map +0 -1
  110. package/build/utils.js +0 -143
  111. package/build/utils.js.map +0 -1
  112. package/src/inlineAudioWebWorker.tsx +0 -340
  113. package/src/utils.ts +0 -189
@@ -0,0 +1,243 @@
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
+ `;
243
+ //# sourceMappingURL=inlineAudioWebWorker.web.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inlineAudioWebWorker.web.js","sourceRoot":"","sources":["../../src/workers/inlineAudioWebWorker.web.tsx"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiPnC,CAAC","sourcesContent":["export const InlineAudioWebWorker = `\nconst DEFAULT_BIT_DEPTH = 32;\nconst DEFAULT_SAMPLE_RATE = 44100;\n\nclass RecorderProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.recordedBuffers = []; // Float32Array\n this.newRecBuffer = []; // Float32Array\n this.resampledBuffer = []; // Float32Array\n this.exportIntervalSamples = 0;\n this.samplesSinceLastExport = 0;\n this.recordSampleRate = DEFAULT_SAMPLE_RATE; // To be overwritten\n this.exportSampleRate = DEFAULT_SAMPLE_RATE; // To be overwritten\n this.recordBitDepth = DEFAULT_BIT_DEPTH; // Default to 32-bit depth\n this.exportBitDepth = DEFAULT_BIT_DEPTH; // To be overwritten\n this.numberOfChannels = 1; // Default to 1 channel (mono)\n this.isRecording = true;\n this.port.onmessage = this.handleMessage.bind(this);\n }\n\n handleMessage(event) {\n switch (event.data.command) {\n case \"init\":\n this.recordSampleRate = event.data.recordSampleRate;\n this.exportSampleRate =\n event.data.exportSampleRate || event.data.recordSampleRate;\n this.exportIntervalSamples =\n this.recordSampleRate * (event.data.interval / 1000);\n if (event.data.numberOfChannels) {\n this.numberOfChannels = event.data.numberOfChannels;\n }\n if (event.data.recordBitDepth) {\n this.recordBitDepth = event.data.recordBitDepth;\n }\n this.exportBitDepth =\n event.data.exportBitDepth || this.recordBitDepth || DEFAULT_BIT_DEPTH;\n break;\n case \"stop\":\n this.isRecording = false;\n this.getAllRecordedData()\n .then((fullRecordedData) => {\n this.port.postMessage({\n command: \"recordedData\",\n recordedData: fullRecordedData,\n bitDepth: this.exportBitDepth,\n sampleRate: this.exportSampleRate,\n });\n return fullRecordedData;\n })\n .catch((error) => {\n console.error(\"Error extracting recorded data:\", error);\n });\n break;\n }\n }\n\n process(inputs, outputs, parameters) {\n if (!this.isRecording) return true;\n const input = inputs[0];\n if (input.length > 0) {\n const newBuffer = new Float32Array(input[0]);\n this.newRecBuffer.push(newBuffer);\n this.recordedBuffers.push(newBuffer);\n this.samplesSinceLastExport += newBuffer.length;\n\n if (this.samplesSinceLastExport >= this.exportIntervalSamples) {\n this.exportNewData();\n this.samplesSinceLastExport = 0;\n }\n }\n return true;\n }\n\n mergeBuffers(bufferArray, recLength) {\n const result = new Float32Array(recLength);\n let offset = 0;\n for (let i = 0; i < bufferArray.length; i++) {\n result.set(bufferArray[i], offset);\n offset += bufferArray[i].length;\n }\n return result;\n }\n\n floatTo16BitPCM(input) {\n const output = new Int16Array(input.length);\n for (let i = 0; i < input.length; i++) {\n const s = Math.max(-1, Math.min(1, input[i]));\n output[i] = s < 0 ? s * 0x8000 : s * 0x7fff;\n }\n console.debug(\n \"Float to 16-bit PCM conversion complete. Output byte length:\",\n output.byteLength,\n );\n return output;\n }\n\n floatTo32BitPCM(input) {\n const output = new Int32Array(input.length);\n for (let i = 0; i < input.length; i++) {\n const s = Math.max(-1, Math.min(1, input[i]));\n output[i] = s < 0 ? s * 0x80000000 : s * 0x7fffffff;\n }\n console.debug(\n \"Float to 32-bit PCM conversion complete. Output byte length:\",\n output.byteLength,\n );\n return output;\n }\n\n resample(samples, targetSampleRate) {\n if (this.recordSampleRate === targetSampleRate) {\n return samples;\n }\n const resampledBuffer = new Float32Array(\n (samples.length * targetSampleRate) / this.recordSampleRate,\n );\n const ratio = this.recordSampleRate / targetSampleRate;\n let offset = 0;\n for (let i = 0; i < resampledBuffer.length; i++) {\n const nextOffset = Math.floor((i + 1) * ratio);\n let accum = 0;\n let count = 0;\n for (let j = offset; j < nextOffset && j < samples.length; j++) {\n accum += samples[j];\n count++;\n }\n resampledBuffer[i] = accum / count;\n offset = nextOffset;\n }\n return resampledBuffer;\n }\n\n async resampleBuffer(buffer, targetSampleRate) {\n if (typeof OfflineAudioContext === \"undefined\") {\n return this.resample(buffer, targetSampleRate);\n }\n\n if (this.recordSampleRate === targetSampleRate) {\n return buffer;\n }\n const offlineContext = new OfflineAudioContext(\n this.numberOfChannels,\n buffer.length,\n this.recordSampleRate,\n );\n const sourceBuffer = offlineContext.createBuffer(\n this.numberOfChannels,\n buffer.length,\n this.recordSampleRate,\n );\n sourceBuffer.copyToChannel(buffer, 0);\n\n const bufferSource = offlineContext.createBufferSource();\n bufferSource.buffer = sourceBuffer;\n bufferSource.connect(offlineContext.destination);\n bufferSource.start();\n\n const renderedBuffer = await offlineContext.startRendering();\n\n const resampledBuffer = new Float32Array(renderedBuffer.length);\n renderedBuffer.copyFromChannel(resampledBuffer, 0);\n\n return resampledBuffer;\n }\n\n async exportNewData() {\n // Calculate the total length of the new recorded buffers\n const length = this.newRecBuffer.reduce(\n (acc, buffer) => acc + buffer.length,\n 0,\n );\n\n // Merge all new recorded buffers into a single buffer\n const mergedBuffer = this.mergeBuffers(this.newRecBuffer, length);\n\n const resampledBuffer = await this.resampleBuffer(\n mergedBuffer,\n this.exportSampleRate,\n );\n\n let finalBuffer = resampledBuffer; // Float32Array\n if (this.recordBitDepth !== this.exportBitDepth) {\n if (this.exportBitDepth === 16) {\n finalBuffer = this.floatTo16BitPCM(resampledBuffer);\n } else if (this.exportBitDepth === 32) {\n finalBuffer = this.floatTo32BitPCM(resampledBuffer);\n }\n }\n\n const originalSize = mergedBuffer.byteLength;\n const resampledSize = resampledBuffer.byteLength;\n const finalSize = finalBuffer.byteLength;\n\n // Clear the new recorded buffers after they have been processed\n this.newRecBuffer.length = 0;\n\n // Post the message to the main thread\n // The first argument is the message data, containing the encoded WAV buffer\n // The second argument is the transfer list, which transfers ownership of the ArrayBuffer\n // to the main thread, avoiding the need to copy the buffer and improving performance\n // this.port.postMessage({ recordedData: encodedWav.buffer, sampleRate: this.recordSampleRate }, [encodedWav.buffer]);\n this.port.postMessage({\n command: \"newData\",\n recordedData: finalBuffer.buffer,\n sampleRate: this.exportSampleRate,\n bitDepth: this.exportBitDepth,\n });\n }\n\n async getAllRecordedData() {\n const length = this.recordedBuffers.reduce(\n (acc, buffer) => acc + buffer.length,\n 0,\n );\n const mergedBuffer = this.mergeBuffers(this.recordedBuffers, length);\n const resampledBuffer = await this.resampleBuffer(\n mergedBuffer,\n this.exportSampleRate,\n );\n // Convert to the desired bit depth if necessary\n let finalBuffer = resampledBuffer;\n if (this.recordBitDepth !== this.exportBitDepth) {\n if (this.exportBitDepth === 16) {\n finalBuffer = this.floatTo16BitPCM(resampledBuffer);\n } else if (this.exportBitDepth === 32) {\n finalBuffer = this.floatTo32BitPCM(resampledBuffer);\n }\n }\n\n const originalSize = mergedBuffer.byteLength;\n const resampledSize = resampledBuffer.byteLength;\n const finalSize = finalBuffer.byteLength;\n\n this.recordedBuffers.length = 0; // Clear the buffers after extraction\n\n return finalBuffer.buffer;\n }\n}\n\nregisterProcessor(\"recorder-processor\", RecorderProcessor);\n`;\n"]}
@@ -32,6 +32,8 @@ class AudioStreamManager: NSObject {
32
32
  internal var recordingFileURL: URL?
33
33
  private var audioProcessor: AudioProcessor?
34
34
  private var startTime: Date?
35
+ private var pauseStartTime: Date?
36
+
35
37
  internal var lastEmissionTime: Date?
36
38
  internal var lastEmittedSize: Int64 = 0
37
39
  private var emissionInterval: TimeInterval = 1.0 // Default to 1 second
@@ -144,8 +146,8 @@ class AudioStreamManager: NSObject {
144
146
 
145
147
  // Calculate the duration in seconds
146
148
  let durationInSeconds = Double(totalDataSize) / (sampleRate * channels * (bitDepth / 8))
147
- let durationInMilliseconds = Int(durationInSeconds * 1000)
148
-
149
+ let durationInMilliseconds = Int(durationInSeconds * 1000) - Int(pausedDuration * 1000)
150
+
149
151
  return [
150
152
  "durationMs": durationInMilliseconds,
151
153
  "isRecording": isRecording,
@@ -192,6 +194,8 @@ class AudioStreamManager: NSObject {
192
194
  lastEmissionTime = Date()
193
195
  accumulatedData.removeAll()
194
196
  totalDataSize = 0
197
+ pausedDuration = 0
198
+ isPaused = false
195
199
 
196
200
  let session = AVAudioSession.sharedInstance()
197
201
  do {
@@ -283,6 +287,39 @@ class AudioStreamManager: NSObject {
283
287
  }
284
288
  }
285
289
 
290
+ /// Pauses the current audio recording.
291
+ func pauseRecording() {
292
+ guard isRecording && !isPaused else {
293
+ Logger.debug("Recording is not in progress or already paused.")
294
+ return
295
+ }
296
+
297
+ audioEngine.pause()
298
+ isPaused = true
299
+ pauseStartTime = Date()
300
+
301
+ Logger.debug("Recording paused.")
302
+ }
303
+
304
+ /// Resumes the current audio recording.
305
+ func resumeRecording() {
306
+ guard isRecording && isPaused else {
307
+ Logger.debug("Recording is not in progress or not paused.")
308
+ return
309
+ }
310
+
311
+ audioEngine.prepare()
312
+ do {
313
+ try audioEngine.start()
314
+ isPaused = false
315
+ if let pauseStartTime = pauseStartTime {
316
+ pausedDuration += Int(Date().timeIntervalSince(pauseStartTime))
317
+ }
318
+ Logger.debug("Recording resumed.")
319
+ } catch {
320
+ Logger.debug("Error: Failed to resume recording: \(error.localizedDescription)")
321
+ }
322
+ }
286
323
 
287
324
  /// Describes the format of the given audio format.
288
325
  /// - Parameter format: The AVAudioFormat object to describe.
@@ -178,6 +178,16 @@ public class ExpoAudioStreamModule: Module, AudioStreamManagerDelegate {
178
178
  return self.streamManager.getStatus()
179
179
  }
180
180
 
181
+ /// Pauses audio recording.
182
+ Function("pauseRecording") {
183
+ self.streamManager.pauseRecording()
184
+ }
185
+
186
+ /// Resumes audio recording.
187
+ Function("resumeRecording") {
188
+ self.streamManager.resumeRecording()
189
+ }
190
+
181
191
  /// Asynchronously stops audio recording and retrieves the recording result.
182
192
  ///
183
193
  /// - Parameters:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@siteed/expo-audio-stream",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "stream audio crossplatform",
5
5
  "license": "MIT",
6
6
  "main": "build/index.js",
@@ -30,18 +30,18 @@
30
30
  "prepublishOnly": "expo-module prepublishOnly",
31
31
  "expo-module": "expo-module",
32
32
  "open:ios": "open -a \"Xcode\" ../../apps/playground/ios",
33
- "open:android": "open -a \"Android Studio\" ../../apps/playground/android"
34
- },
35
- "dependencies": {
36
- "react-native-quick-base64": "^2.1.2"
33
+ "open:android": "open -a \"Android Studio\" ../../apps/playground/android",
34
+ "size": "bundle-size && size-limit"
37
35
  },
38
36
  "devDependencies": {
39
37
  "@expo/config-plugins": "^7.9.1",
38
+ "@size-limit/preset-big-lib": "^11.1.4",
40
39
  "@types/debug": "^4.1.12",
41
40
  "@types/node": "^20.12.7",
42
41
  "@types/react": "^18.0.25",
43
42
  "@typescript-eslint/eslint-plugin": "^7.7.0",
44
43
  "@typescript-eslint/parser": "^7.7.0",
44
+ "bundle-size": "^1.1.5",
45
45
  "eslint": "^8.56.0",
46
46
  "eslint-config-prettier": "^9.1.0",
47
47
  "eslint-config-universe": "^12.0.0",
@@ -52,7 +52,8 @@
52
52
  "expo-module-scripts": "^3.5.2",
53
53
  "expo-modules-core": "^1.12.19",
54
54
  "prettier": "^3.2.5",
55
- "react-native": "^0.74.3"
55
+ "react-native": "^0.74.3",
56
+ "size-limit": "^11.1.4"
56
57
  },
57
58
  "peerDependencies": {
58
59
  "expo": "*",
@@ -5,7 +5,7 @@
5
5
  "rootDir": "src"
6
6
  },
7
7
  "include": [
8
- "./src"
8
+ "./src",
9
9
  ],
10
10
  "exclude": [
11
11
  "**/__mocks__/*",
package/publish.sh CHANGED
File without changes
@@ -0,0 +1,85 @@
1
+ // packages/expo-audio-stream/src/AudioAnalysis/AudioAnalysis.types.ts
2
+
3
+ /**
4
+ * Represents various audio features extracted from an audio signal.
5
+ */
6
+ export interface AudioFeatures {
7
+ energy: number; // The infinite integral of the squared signal, representing the overall energy of the audio.
8
+ mfcc: number[]; // Mel-frequency cepstral coefficients, describing the short-term power spectrum of a sound.
9
+ rms: number; // Root mean square value, indicating the amplitude of the audio signal.
10
+ minAmplitude: number; // Minimum amplitude value in the audio signal.
11
+ maxAmplitude: number; // Maximum amplitude value in the audio signal.
12
+ zcr: number; // Zero-crossing rate, indicating the rate at which the signal changes sign.
13
+ spectralCentroid: number; // The center of mass of the spectrum, indicating the brightness of the sound.
14
+ spectralFlatness: number; // Measure of the flatness of the spectrum, indicating how noise-like the signal is.
15
+ spectralRolloff: number; // The frequency below which a specified percentage (usually 85%) of the total spectral energy lies.
16
+ spectralBandwidth: number; // The width of the spectrum, indicating the range of frequencies present.
17
+ chromagram: number[]; // Chromagram, representing the 12 different pitch classes of the audio.
18
+ tempo: number; // Estimated tempo of the audio signal, measured in beats per minute (BPM).
19
+ hnr: number; // Harmonics-to-noise ratio, indicating the proportion of harmonics to noise in the audio signal.
20
+ }
21
+
22
+ /**
23
+ * Options to specify which audio features to extract.
24
+ */
25
+ export interface AudioFeaturesOptions {
26
+ energy?: boolean;
27
+ mfcc?: boolean;
28
+ rms?: boolean;
29
+ zcr?: boolean;
30
+ spectralCentroid?: boolean;
31
+ spectralFlatness?: boolean;
32
+ spectralRolloff?: boolean;
33
+ spectralBandwidth?: boolean;
34
+ chromagram?: boolean;
35
+ tempo?: boolean;
36
+ hnr?: boolean;
37
+ }
38
+
39
+ /**
40
+ * Represents a single data point in the audio analysis.
41
+ */
42
+ export interface DataPoint {
43
+ id: number;
44
+ amplitude: number;
45
+ activeSpeech?: boolean;
46
+ dB?: number;
47
+ silent?: boolean;
48
+ features?: AudioFeatures;
49
+ startTime?: number;
50
+ endTime?: number;
51
+ // start / end position in bytes
52
+ startPosition?: number;
53
+ endPosition?: number;
54
+ // number of audio samples for this point (samples size depends on bit depth)
55
+ samples?: number;
56
+ // TODO: speaker detection
57
+ speaker?: number;
58
+ }
59
+
60
+ /**
61
+ * Represents the complete data from the audio analysis.
62
+ */
63
+ export interface AudioAnalysisData {
64
+ pointsPerSecond: number; // How many consolidated value per second
65
+ durationMs: number; // Duration of the audio in milliseconds
66
+ bitDepth: number; // Bit depth of the audio
67
+ samples: number; // Size of the audio in bytes
68
+ numberOfChannels: number; // Number of audio channels
69
+ sampleRate: number; // Sample rate of the audio
70
+ dataPoints: DataPoint[]; // Array of data points from the analysis.
71
+ amplitudeRange: {
72
+ min: number;
73
+ max: number;
74
+ };
75
+ // TODO: speaker detection
76
+ speakerChanges?: {
77
+ timestamp: number; // Timestamp of the speaker change in milliseconds.
78
+ speaker: number; // Speaker identifier.
79
+ }[];
80
+ }
81
+
82
+ export interface AudioAnalysisEventPayload {
83
+ analysis: AudioAnalysisData;
84
+ visualizationDuration: number;
85
+ }
@@ -0,0 +1,136 @@
1
+ // packages/expo-audio-stream/src/AudioAnalysis/extractAudioAnalysis.ts
2
+ import { AudioAnalysisData } from "./AudioAnalysis.types";
3
+ import ExpoAudioStreamModule from "../ExpoAudioStreamModule";
4
+ import { isWeb } from "../constants";
5
+ import { getLogger } from "../logger";
6
+ import { ExtractMetadataProps } from "../useAudioRecorder";
7
+ import { convertPCMToFloat32 } from "../utils/convertPCMToFloat32";
8
+ import { getWavFileInfo } from "../utils/getWavFileInfo";
9
+ import { InlineFeaturesExtractor } from "../workers/InlineFeaturesExtractor.web";
10
+
11
+ const logger = getLogger("extractAudioAnalysis");
12
+
13
+ export const extractAudioAnalysis = async ({
14
+ fileUri,
15
+ pointsPerSecond = 20,
16
+ arrayBuffer,
17
+ bitDepth,
18
+ skipWavHeader,
19
+ durationMs,
20
+ sampleRate,
21
+ numberOfChannels,
22
+ algorithm = "rms",
23
+ features,
24
+ featuresExtratorUrl,
25
+ }: ExtractMetadataProps): Promise<AudioAnalysisData> => {
26
+ if (isWeb) {
27
+ if (!arrayBuffer && !fileUri) {
28
+ throw new Error("Either arrayBuffer or fileUri must be provided");
29
+ }
30
+
31
+ if (!arrayBuffer) {
32
+ logger.log(`fetching fileUri`, fileUri);
33
+ const response = await fetch(fileUri!);
34
+
35
+ if (!response.ok) {
36
+ throw new Error(`Failed to fetch fileUri: ${response.statusText}`);
37
+ }
38
+
39
+ arrayBuffer = (await response.arrayBuffer()).slice(0);
40
+ logger.log(`fetched fileUri`, arrayBuffer.byteLength, arrayBuffer);
41
+ }
42
+
43
+ // Create a new copy of the ArrayBuffer to avoid detachment issues
44
+ const bufferCopy = arrayBuffer.slice(0);
45
+ logger.log(
46
+ `extractAudioAnalysis skipWavHeader=${skipWavHeader} bitDepth=${bitDepth} len=${bufferCopy.byteLength}`,
47
+ bufferCopy.slice(0, 100),
48
+ );
49
+
50
+ let actualBitDepth = bitDepth;
51
+ if (!actualBitDepth) {
52
+ logger.log(
53
+ `extractAudioAnalysis bitDepth not provided -- getting wav file info`,
54
+ );
55
+ const fileInfo = await getWavFileInfo(bufferCopy);
56
+ actualBitDepth = fileInfo.bitDepth;
57
+ }
58
+ logger.log(`extractAudioAnalysis actualBitDepth=${actualBitDepth}`);
59
+ // let copyChannelData: Float32Array;
60
+ // try {
61
+ // const audioContext = new (window.AudioContext ||
62
+ // // @ts-ignore
63
+ // window.webkitAudioContext)();
64
+ // const audioBuffer = await audioContext.decodeAudioData(bufferCopy);
65
+ // const channelData = audioBuffer.getChannelData(0); // Use only the first channel
66
+ // copyChannelData = new Float32Array(channelData); // Create a new Float32Array
67
+ // } catch (error) {
68
+ // console.warn("Failed to decode audio data:", error);
69
+ // // Fall back to creating a new Float32Array from the ArrayBuffer if decoding fails
70
+ // copyChannelData = new Float32Array(arrayBuffer);
71
+ // }
72
+
73
+ const {
74
+ pcmValues: channelData,
75
+ min,
76
+ max,
77
+ } = convertPCMToFloat32({
78
+ buffer: arrayBuffer,
79
+ bitDepth: actualBitDepth,
80
+ skipWavHeader,
81
+ });
82
+ logger.log(
83
+ `extractAudioAnalysis skipWaveHeader=${skipWavHeader} convertPCMToFloat32 length=${channelData.length} range: [ ${min} :: ${max} ]`,
84
+ );
85
+
86
+ return new Promise((resolve, reject) => {
87
+ let worker: Worker;
88
+ if (featuresExtratorUrl) {
89
+ worker = new Worker(new URL(featuresExtratorUrl, window.location.href));
90
+ } else {
91
+ const blob = new Blob([InlineFeaturesExtractor], {
92
+ type: "application/javascript",
93
+ });
94
+ const url = URL.createObjectURL(blob);
95
+ worker = new Worker(url);
96
+ }
97
+
98
+ worker.onmessage = (event) => {
99
+ resolve(event.data.result);
100
+ };
101
+
102
+ worker.onerror = (error) => {
103
+ reject(error);
104
+ };
105
+
106
+ worker.postMessage({
107
+ command: "process",
108
+ channelData,
109
+ sampleRate,
110
+ pointsPerSecond,
111
+ algorithm,
112
+ bitDepth,
113
+ fullAudioDurationMs: durationMs,
114
+ numberOfChannels,
115
+ });
116
+ });
117
+ } else {
118
+ if (!fileUri) {
119
+ throw new Error("fileUri is required");
120
+ }
121
+ logger.log(`extractAudioAnalysis`, {
122
+ fileUri,
123
+ pointsPerSecond,
124
+ algorithm,
125
+ });
126
+ const res = await ExpoAudioStreamModule.extractAudioAnalysis({
127
+ fileUri,
128
+ pointsPerSecond,
129
+ skipWavHeader,
130
+ algorithm,
131
+ features,
132
+ });
133
+ logger.log(`extractAudioAnalysis`, res);
134
+ return res;
135
+ }
136
+ };
@@ -0,0 +1,25 @@
1
+ import ExpoAudioStreamModule from "../ExpoAudioStreamModule";
2
+ import { getLogger } from "../logger";
3
+
4
+ const logger = getLogger("extractWaveform");
5
+ export interface ExtractWaveformProps {
6
+ fileUri: string;
7
+ numberOfSamples: number;
8
+ offset?: number;
9
+ length?: number;
10
+ }
11
+ export const extractWaveform = async ({
12
+ fileUri,
13
+ numberOfSamples,
14
+ offset = 0,
15
+ length,
16
+ }: ExtractWaveformProps): Promise<unknown> => {
17
+ const res = await ExpoAudioStreamModule.extractAudioAnalysis({
18
+ fileUri,
19
+ numberOfSamples,
20
+ offset,
21
+ length,
22
+ });
23
+ logger.log(`extractWaveform`, res);
24
+ return res;
25
+ };