@siteed/expo-audio-stream 1.0.2 → 1.0.5

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 (139) hide show
  1. package/.size-limit.json +6 -0
  2. package/README.md +18 -176
  3. package/android/src/main/java/net/siteed/audiostream/AudioRecorderManager.kt +1 -0
  4. package/app.plugin.js +1 -1
  5. package/build/AudioAnalysis/AudioAnalysis.types.d.ts +74 -0
  6. package/build/AudioAnalysis/AudioAnalysis.types.d.ts.map +1 -0
  7. package/build/AudioAnalysis/AudioAnalysis.types.js +3 -0
  8. package/build/AudioAnalysis/AudioAnalysis.types.js.map +1 -0
  9. package/build/AudioAnalysis/extractAudioAnalysis.d.ts +20 -0
  10. package/build/AudioAnalysis/extractAudioAnalysis.d.ts.map +1 -0
  11. package/build/AudioAnalysis/extractAudioAnalysis.js +88 -0
  12. package/build/AudioAnalysis/extractAudioAnalysis.js.map +1 -0
  13. package/build/AudioAnalysis/extractWaveform.d.ts +8 -0
  14. package/build/AudioAnalysis/extractWaveform.d.ts.map +1 -0
  15. package/build/AudioAnalysis/extractWaveform.js +14 -0
  16. package/build/AudioAnalysis/extractWaveform.js.map +1 -0
  17. package/build/AudioRecorder.provider.d.ts +15 -2
  18. package/build/AudioRecorder.provider.d.ts.map +1 -1
  19. package/build/AudioRecorder.provider.js +21 -8
  20. package/build/AudioRecorder.provider.js.map +1 -1
  21. package/build/ExpoAudioStream.native.d.ts.map +1 -1
  22. package/build/ExpoAudioStream.native.js +2 -2
  23. package/build/ExpoAudioStream.native.js.map +1 -1
  24. package/build/ExpoAudioStream.types.d.ts +33 -89
  25. package/build/ExpoAudioStream.types.d.ts.map +1 -1
  26. package/build/ExpoAudioStream.types.js.map +1 -1
  27. package/build/ExpoAudioStream.web.d.ts +10 -9
  28. package/build/ExpoAudioStream.web.d.ts.map +1 -1
  29. package/build/ExpoAudioStream.web.js +44 -25
  30. package/build/ExpoAudioStream.web.js.map +1 -1
  31. package/build/ExpoAudioStreamModule.d.ts.map +1 -1
  32. package/build/ExpoAudioStreamModule.js +13 -8
  33. package/build/ExpoAudioStreamModule.js.map +1 -1
  34. package/build/{WebRecorder.d.ts → WebRecorder.web.d.ts} +13 -9
  35. package/build/WebRecorder.web.d.ts.map +1 -0
  36. package/build/{WebRecorder.js → WebRecorder.web.js} +118 -63
  37. package/build/WebRecorder.web.js.map +1 -0
  38. package/build/constants.d.ts +11 -0
  39. package/build/constants.d.ts.map +1 -0
  40. package/build/constants.js +14 -0
  41. package/build/constants.js.map +1 -0
  42. package/build/events.d.ts +18 -0
  43. package/build/events.d.ts.map +1 -0
  44. package/build/events.js +15 -0
  45. package/build/events.js.map +1 -0
  46. package/build/index.d.ts +9 -17
  47. package/build/index.d.ts.map +1 -1
  48. package/build/index.js +7 -113
  49. package/build/index.js.map +1 -1
  50. package/build/logger.d.ts +9 -0
  51. package/build/logger.d.ts.map +1 -0
  52. package/build/logger.js +13 -0
  53. package/build/logger.js.map +1 -0
  54. package/build/useAudioRecorder.d.ts +20 -0
  55. package/build/useAudioRecorder.d.ts.map +1 -0
  56. package/build/{useAudioRecording.js → useAudioRecorder.js} +90 -86
  57. package/build/useAudioRecorder.js.map +1 -0
  58. package/build/utils/BlobFix.d.ts +9 -0
  59. package/build/utils/BlobFix.d.ts.map +1 -0
  60. package/build/utils/BlobFix.js +494 -0
  61. package/build/utils/BlobFix.js.map +1 -0
  62. package/build/utils/concatenateBuffers.d.ts +8 -0
  63. package/build/utils/concatenateBuffers.d.ts.map +1 -0
  64. package/build/utils/concatenateBuffers.js +21 -0
  65. package/build/utils/concatenateBuffers.js.map +1 -0
  66. package/build/utils/convertPCMToFloat32.d.ts +11 -0
  67. package/build/utils/convertPCMToFloat32.d.ts.map +1 -0
  68. package/build/utils/convertPCMToFloat32.js +54 -0
  69. package/build/utils/convertPCMToFloat32.js.map +1 -0
  70. package/build/utils/encodingToBitDepth.d.ts +5 -0
  71. package/build/utils/encodingToBitDepth.d.ts.map +1 -0
  72. package/build/utils/encodingToBitDepth.js +13 -0
  73. package/build/utils/encodingToBitDepth.js.map +1 -0
  74. package/build/utils/getWavFileInfo.d.ts +26 -0
  75. package/build/utils/getWavFileInfo.d.ts.map +1 -0
  76. package/build/utils/getWavFileInfo.js +92 -0
  77. package/build/utils/getWavFileInfo.js.map +1 -0
  78. package/build/utils/writeWavHeader.d.ts +9 -0
  79. package/build/utils/writeWavHeader.d.ts.map +1 -0
  80. package/build/utils/writeWavHeader.js +41 -0
  81. package/build/utils/writeWavHeader.js.map +1 -0
  82. package/build/workers/InlineFeaturesExtractor.web.d.ts +2 -0
  83. package/build/workers/InlineFeaturesExtractor.web.d.ts.map +1 -0
  84. package/build/workers/InlineFeaturesExtractor.web.js +303 -0
  85. package/build/workers/InlineFeaturesExtractor.web.js.map +1 -0
  86. package/build/workers/inlineAudioWebWorker.web.d.ts +2 -0
  87. package/build/workers/inlineAudioWebWorker.web.d.ts.map +1 -0
  88. package/build/workers/inlineAudioWebWorker.web.js +243 -0
  89. package/build/workers/inlineAudioWebWorker.web.js.map +1 -0
  90. package/expo-module.config.json +8 -17
  91. package/ios/AudioStreamManager.swift +40 -2
  92. package/ios/ExpoAudioStreamModule.swift +11 -0
  93. package/ios/RecordingResult.swift +1 -0
  94. package/package.json +72 -64
  95. package/plugin/build/index.d.ts +1 -1
  96. package/plugin/build/index.js +7 -7
  97. package/plugin/src/index.ts +47 -47
  98. package/plugin/tsconfig.json +8 -13
  99. package/publish.sh +0 -0
  100. package/src/AudioAnalysis/AudioAnalysis.types.ts +84 -0
  101. package/src/AudioAnalysis/extractAudioAnalysis.ts +147 -0
  102. package/src/AudioAnalysis/extractWaveform.ts +25 -0
  103. package/src/AudioRecorder.provider.tsx +59 -31
  104. package/src/ExpoAudioStream.native.ts +2 -2
  105. package/src/ExpoAudioStream.types.ts +58 -116
  106. package/src/ExpoAudioStream.web.ts +233 -205
  107. package/src/ExpoAudioStreamModule.ts +18 -12
  108. package/src/WebRecorder.web.ts +433 -0
  109. package/src/constants.ts +18 -0
  110. package/src/events.ts +39 -0
  111. package/src/index.ts +15 -176
  112. package/src/logger.ts +23 -0
  113. package/src/useAudioRecorder.tsx +420 -0
  114. package/src/utils/BlobFix.ts +550 -0
  115. package/src/utils/concatenateBuffers.ts +24 -0
  116. package/src/utils/convertPCMToFloat32.ts +75 -0
  117. package/src/utils/encodingToBitDepth.ts +18 -0
  118. package/src/utils/getWavFileInfo.ts +132 -0
  119. package/src/utils/writeWavHeader.ts +56 -0
  120. package/src/workers/InlineFeaturesExtractor.web.tsx +302 -0
  121. package/src/workers/inlineAudioWebWorker.web.tsx +242 -0
  122. package/tsconfig.json +12 -7
  123. package/build/WebRecorder.d.ts.map +0 -1
  124. package/build/WebRecorder.js.map +0 -1
  125. package/build/inlineAudioWebWorker.d.ts +0 -3
  126. package/build/inlineAudioWebWorker.d.ts.map +0 -1
  127. package/build/inlineAudioWebWorker.js +0 -340
  128. package/build/inlineAudioWebWorker.js.map +0 -1
  129. package/build/useAudioRecording.d.ts +0 -38
  130. package/build/useAudioRecording.d.ts.map +0 -1
  131. package/build/useAudioRecording.js.map +0 -1
  132. package/build/utils.d.ts +0 -31
  133. package/build/utils.d.ts.map +0 -1
  134. package/build/utils.js +0 -143
  135. package/build/utils.js.map +0 -1
  136. package/src/WebRecorder.ts +0 -364
  137. package/src/inlineAudioWebWorker.tsx +0 -340
  138. package/src/useAudioRecording.tsx +0 -410
  139. package/src/utils.ts +0 -189
package/src/index.ts CHANGED
@@ -1,183 +1,22 @@
1
1
  // src/index.ts
2
- import { EventEmitter, type Subscription } from "expo-modules-core";
3
- import { Platform } from "react-native";
4
2
 
5
- // Import the native module. On web, it will be resolved to ExpoAudioStream.web.ts
6
- // and on native platforms to ExpoAudioStream.ts
3
+ import { extractAudioAnalysis } from './AudioAnalysis/extractAudioAnalysis'
7
4
  import {
8
- AudioRecorderProvider,
9
- useSharedAudioRecorder,
10
- } from "./AudioRecorder.provider";
11
- import { AudioAnalysisData, AudioEventPayload } from "./ExpoAudioStream.types";
12
- import ExpoAudioStreamModule from "./ExpoAudioStreamModule";
13
- import { ExtractMetadataProps, useAudioRecorder } from "./useAudioRecording";
14
- import { convertPCMToFloat32, getWavFileInfo, writeWavHeader } from "./utils";
5
+ AudioRecorderProvider,
6
+ useSharedAudioRecorder,
7
+ } from './AudioRecorder.provider'
8
+ import { useAudioRecorder } from './useAudioRecorder'
15
9
 
16
- const emitter = new EventEmitter(ExpoAudioStreamModule);
17
-
18
- export function addAudioEventListener(
19
- listener: (event: AudioEventPayload) => Promise<void>,
20
- ): Subscription {
21
- console.log(`addAudioEventListener`, listener);
22
- return emitter.addListener<AudioEventPayload>("AudioData", listener);
23
- }
24
-
25
- export function addAudioAnalysisListener(
26
- listener: (event: AudioAnalysisData) => Promise<void>,
27
- ): Subscription {
28
- console.log(`addAudioAnalysisListener`, listener);
29
- return emitter.addListener<AudioAnalysisData>("AudioAnalysis", listener);
30
- }
31
-
32
- const isWeb = Platform.OS === "web";
33
-
34
- export const extractAudioAnalysis = async ({
35
- fileUri,
36
- pointsPerSecond = 20,
37
- arrayBuffer,
38
- bitDepth,
39
- skipWavHeader,
40
- durationMs,
41
- sampleRate,
42
- numberOfChannels,
43
- algorithm = "rms",
44
- features,
45
- featuresExtratorUrl = "/audio-features-extractor.js",
46
- }: ExtractMetadataProps): Promise<AudioAnalysisData> => {
47
- if (isWeb) {
48
- if (!arrayBuffer && !fileUri) {
49
- throw new Error("Either arrayBuffer or fileUri must be provided");
50
- }
51
-
52
- if (!arrayBuffer) {
53
- console.log(`fetching fileUri`, fileUri);
54
- const response = await fetch(fileUri!);
55
-
56
- if (!response.ok) {
57
- throw new Error(`Failed to fetch fileUri: ${response.statusText}`);
58
- }
59
-
60
- arrayBuffer = (await response.arrayBuffer()).slice(0);
61
- console.log(`fetched fileUri`, arrayBuffer.byteLength, arrayBuffer);
62
- }
63
-
64
- // Create a new copy of the ArrayBuffer to avoid detachment issues
65
- const bufferCopy = arrayBuffer.slice(0);
66
- console.log(
67
- `extractAudioAnalysis skipWavHeader=${skipWavHeader} bitDepth=${bitDepth} len=${bufferCopy.byteLength}`,
68
- bufferCopy.slice(0, 100),
69
- );
70
-
71
- let actualBitDepth = bitDepth;
72
- if (!actualBitDepth) {
73
- console.log(
74
- `extractAudioAnalysis bitDepth not provided -- getting wav file info`,
75
- );
76
- const fileInfo = await getWavFileInfo(bufferCopy);
77
- actualBitDepth = fileInfo.bitDepth;
78
- }
79
- console.log(`extractAudioAnalysis actualBitDepth=${actualBitDepth}`);
80
- // let copyChannelData: Float32Array;
81
- // try {
82
- // const audioContext = new (window.AudioContext ||
83
- // // @ts-ignore
84
- // window.webkitAudioContext)();
85
- // const audioBuffer = await audioContext.decodeAudioData(bufferCopy);
86
- // const channelData = audioBuffer.getChannelData(0); // Use only the first channel
87
- // copyChannelData = new Float32Array(channelData); // Create a new Float32Array
88
- // } catch (error) {
89
- // console.warn("Failed to decode audio data:", error);
90
- // // Fall back to creating a new Float32Array from the ArrayBuffer if decoding fails
91
- // copyChannelData = new Float32Array(arrayBuffer);
92
- // }
93
-
94
- const {
95
- pcmValues: channelData,
96
- min,
97
- max,
98
- } = convertPCMToFloat32({
99
- buffer: arrayBuffer,
100
- bitDepth: actualBitDepth,
101
- skipWavHeader,
102
- });
103
- console.log(
104
- `extractAudioAnalysis skipWaveHeader=${skipWavHeader} convertPCMToFloat32 length=${channelData.length} range: [ ${min} :: ${max} ]`,
105
- );
106
-
107
- return new Promise((resolve, reject) => {
108
- const worker = new Worker(
109
- new URL(featuresExtratorUrl, window.location.href),
110
- );
111
-
112
- worker.onmessage = (event) => {
113
- resolve(event.data.result);
114
- };
115
-
116
- worker.onerror = (error) => {
117
- reject(error);
118
- };
119
-
120
- worker.postMessage({
121
- command: "process",
122
- channelData,
123
- sampleRate,
124
- pointsPerSecond,
125
- algorithm,
126
- bitDepth,
127
- fullAudioDurationMs: durationMs,
128
- numberOfChannels,
129
- });
130
- });
131
- } else {
132
- if (!fileUri) {
133
- throw new Error("fileUri is required");
134
- }
135
- console.log(`extractAudioAnalysis`, {
136
- fileUri,
137
- pointsPerSecond,
138
- algorithm,
139
- });
140
- const res = await ExpoAudioStreamModule.extractAudioAnalysis({
141
- fileUri,
142
- pointsPerSecond,
143
- skipWavHeader,
144
- algorithm,
145
- features,
146
- });
147
- console.log(`extractAudioAnalysis`, res);
148
- return res;
149
- }
150
- };
151
-
152
- export interface ExtractWaveformProps {
153
- fileUri: string;
154
- numberOfSamples: number;
155
- offset?: number;
156
- length?: number;
157
- }
158
- export const extractWaveform = async ({
159
- fileUri,
160
- numberOfSamples,
161
- offset = 0,
162
- length,
163
- }: ExtractWaveformProps): Promise<unknown> => {
164
- const res = await ExpoAudioStreamModule.extractAudioAnalysis({
165
- fileUri,
166
- numberOfSamples,
167
- offset,
168
- length,
169
- });
170
- console.log(`extractWaveform`, res);
171
- return res;
172
- };
10
+ export * from './utils/getWavFileInfo'
11
+ export * from './utils/convertPCMToFloat32'
12
+ export * from './utils/writeWavHeader'
173
13
 
174
14
  export {
175
- AudioRecorderProvider,
176
- convertPCMToFloat32,
177
- getWavFileInfo,
178
- useAudioRecorder,
179
- useSharedAudioRecorder,
180
- writeWavHeader as writeWaveHeader,
181
- };
15
+ AudioRecorderProvider,
16
+ extractAudioAnalysis,
17
+ useAudioRecorder,
18
+ useSharedAudioRecorder,
19
+ }
182
20
 
183
- export * from "./ExpoAudioStream.types";
21
+ export type * from './AudioAnalysis/AudioAnalysis.types'
22
+ export type * from './ExpoAudioStream.types'
package/src/logger.ts ADDED
@@ -0,0 +1,23 @@
1
+ // packages/expo-audio-stream/src/logger.ts
2
+ import { getLogger as siteedGetLogger } from '@siteed/react-native-logger'
3
+
4
+ import { DEBUG_NAMESPACE } from './constants'
5
+
6
+ type ConsoleLike = {
7
+ log: (message: string, ...args: unknown[]) => void
8
+ debug: (message: string, ...args: unknown[]) => void
9
+ warn: (message: string, ...args: unknown[]) => void
10
+ error: (message: string, ...args: unknown[]) => void
11
+ }
12
+
13
+ export const getLogger = (tag: string): ConsoleLike => {
14
+ const baseLogger = siteedGetLogger(`${DEBUG_NAMESPACE}:${tag}`)
15
+
16
+ return {
17
+ log: (...args: unknown[]) => baseLogger.log(...(args as [unknown])),
18
+ debug: (...args: unknown[]) => baseLogger.debug(...(args as [unknown])),
19
+ error: (...args: unknown[]) => baseLogger.error(...(args as [unknown])),
20
+ warn: (...args: unknown[]) => baseLogger.warn(...(args as [unknown])),
21
+ }
22
+ }
23
+
@@ -0,0 +1,420 @@
1
+ // src/useAudioRecorder.ts
2
+ import { Platform, Subscription } from 'expo-modules-core'
3
+ import { useCallback, useEffect, useReducer, useRef } from 'react'
4
+
5
+ import { AudioAnalysis } from './AudioAnalysis/AudioAnalysis.types'
6
+ import {
7
+ AudioDataEvent,
8
+ AudioRecording,
9
+ AudioStreamStatus,
10
+ RecordingConfig,
11
+ StartRecordingResult,
12
+ } from './ExpoAudioStream.types'
13
+ import ExpoAudioStreamModule from './ExpoAudioStreamModule'
14
+ import {
15
+ addAudioAnalysisListener,
16
+ addAudioEventListener,
17
+ AudioEventPayload,
18
+ } from './events'
19
+ import { getLogger } from './logger'
20
+
21
+ const TAG = 'useAudioRecorder'
22
+ const logger = getLogger(TAG)
23
+ export interface UseAudioRecorderProps {
24
+ debug?: boolean
25
+ audioWorkletUrl?: string
26
+ featuresExtratorUrl?: string
27
+ }
28
+
29
+ export interface UseAudioRecorderState {
30
+ startRecording: (_: RecordingConfig) => Promise<StartRecordingResult>
31
+ stopRecording: () => Promise<AudioRecording>
32
+ pauseRecording: () => void
33
+ resumeRecording: () => void
34
+ isRecording: boolean
35
+ isPaused: boolean
36
+ durationMs: number // Duration of the recording
37
+ size: number // Size in bytes of the recorded audio
38
+ analysisData?: AudioAnalysis
39
+ }
40
+
41
+ interface RecorderReducerState {
42
+ isRecording: boolean
43
+ isPaused: boolean
44
+ durationMs: number
45
+ size: number
46
+ analysisData?: AudioAnalysis
47
+ }
48
+
49
+ type RecorderAction =
50
+ | { type: 'START' | 'STOP' | 'PAUSE' | 'RESUME' }
51
+ | { type: 'UPDATE_STATUS'; payload: { durationMs: number; size: number } }
52
+ | { type: 'UPDATE_ANALYSIS'; payload: AudioAnalysis }
53
+
54
+ const defaultAnalysis: AudioAnalysis = {
55
+ pointsPerSecond: 10,
56
+ bitDepth: 32,
57
+ numberOfChannels: 1,
58
+ durationMs: 0,
59
+ sampleRate: 44100,
60
+ samples: 0,
61
+ dataPoints: [],
62
+ amplitudeAlgorithm: 'rms',
63
+ speakerChanges: [],
64
+ amplitudeRange: {
65
+ min: Number.POSITIVE_INFINITY,
66
+ max: Number.NEGATIVE_INFINITY,
67
+ },
68
+ }
69
+
70
+ function audioRecorderReducer(
71
+ state: RecorderReducerState,
72
+ action: RecorderAction
73
+ ): RecorderReducerState {
74
+ switch (action.type) {
75
+ case 'START':
76
+ return {
77
+ ...state,
78
+ isRecording: true,
79
+ isPaused: false,
80
+ durationMs: 0,
81
+ size: 0,
82
+ analysisData: defaultAnalysis, // Reset analysis data
83
+ }
84
+ case 'STOP':
85
+ return { ...state, isRecording: false, isPaused: false }
86
+ case 'PAUSE':
87
+ return { ...state, isPaused: true, isRecording: false }
88
+ case 'RESUME':
89
+ return { ...state, isPaused: false, isRecording: true }
90
+ case 'UPDATE_STATUS':
91
+ return {
92
+ ...state,
93
+ durationMs: action.payload.durationMs,
94
+ size: action.payload.size,
95
+ }
96
+ case 'UPDATE_ANALYSIS':
97
+ return {
98
+ ...state,
99
+ analysisData: action.payload,
100
+ }
101
+ default:
102
+ return state
103
+ }
104
+ }
105
+
106
+ interface HandleAudioAnalysisProps {
107
+ analysis: AudioAnalysis
108
+ visualizationDuration: number
109
+ }
110
+
111
+ export function useAudioRecorder({
112
+ debug = false,
113
+ audioWorkletUrl,
114
+ featuresExtratorUrl,
115
+ }: UseAudioRecorderProps = {}): UseAudioRecorderState {
116
+ const [state, dispatch] = useReducer(audioRecorderReducer, {
117
+ isRecording: false,
118
+ isPaused: false,
119
+ durationMs: 0,
120
+ size: 0,
121
+ analysisData: undefined,
122
+ })
123
+
124
+ const analysisListenerRef = useRef<Subscription | null>(null)
125
+ const analysisRef = useRef<AudioAnalysis>({ ...defaultAnalysis })
126
+
127
+ // Instantiate the module for web with URLs
128
+ const ExpoAudioStream =
129
+ Platform.OS === 'web'
130
+ ? ExpoAudioStreamModule({ audioWorkletUrl, featuresExtratorUrl })
131
+ : ExpoAudioStreamModule
132
+
133
+ const onAudioStreamRef = useRef<
134
+ ((_: AudioDataEvent) => Promise<void>) | null
135
+ >(null)
136
+
137
+ const handleAudioAnalysis = useCallback(
138
+ async ({
139
+ analysis,
140
+ visualizationDuration,
141
+ }: HandleAudioAnalysisProps) => {
142
+ const savedAnalysisData = analysisRef.current || {
143
+ ...defaultAnalysis,
144
+ }
145
+
146
+ const maxDuration = visualizationDuration
147
+
148
+ logger.debug(
149
+ `[handleAudioAnalysis] Received audio analysis: maxDuration=${maxDuration} analysis.dataPoints=${analysis.dataPoints.length} analysisData.dataPoints=${savedAnalysisData.dataPoints.length}`,
150
+ analysis
151
+ )
152
+
153
+ // Combine data points
154
+ const combinedDataPoints = [
155
+ ...savedAnalysisData.dataPoints,
156
+ ...analysis.dataPoints,
157
+ ]
158
+
159
+ // Calculate the new duration
160
+ const pointsPerSecond =
161
+ analysis.pointsPerSecond || savedAnalysisData.pointsPerSecond
162
+ const maxDataPoints =
163
+ (pointsPerSecond * visualizationDuration) / 1000
164
+
165
+ logger.debug(
166
+ `[handleAudioAnalysis] Combined data points before trimming: pointsPerSecond=${pointsPerSecond} visualizationDuration=${visualizationDuration} combinedDataPointsLength=${combinedDataPoints.length} vs maxDataPoints=${maxDataPoints}`
167
+ )
168
+
169
+ // Trim data points to keep within the maximum number of data points
170
+ if (combinedDataPoints.length > maxDataPoints) {
171
+ combinedDataPoints.splice(
172
+ 0,
173
+ combinedDataPoints.length - maxDataPoints
174
+ )
175
+ }
176
+
177
+ savedAnalysisData.dataPoints = combinedDataPoints
178
+ savedAnalysisData.bitDepth =
179
+ analysis.bitDepth || savedAnalysisData.bitDepth
180
+ savedAnalysisData.durationMs =
181
+ combinedDataPoints.length * (1000 / pointsPerSecond)
182
+
183
+ // Update amplitude range
184
+ const newMin = Math.min(
185
+ savedAnalysisData.amplitudeRange.min,
186
+ analysis.amplitudeRange.min
187
+ )
188
+ const newMax = Math.max(
189
+ savedAnalysisData.amplitudeRange.max,
190
+ analysis.amplitudeRange.max
191
+ )
192
+
193
+ savedAnalysisData.amplitudeRange = {
194
+ min: newMin,
195
+ max: newMax,
196
+ }
197
+
198
+ logger.debug(
199
+ `[handleAudioAnalysis] Updated analysis data: durationMs=${savedAnalysisData.durationMs}`,
200
+ savedAnalysisData
201
+ )
202
+
203
+ // Update the ref
204
+ analysisRef.current = savedAnalysisData
205
+
206
+ // Dispatch the updated analysis data to state to trigger re-render
207
+ // need to use spread operator otherwise it doesnt trigger update.
208
+ dispatch({
209
+ type: 'UPDATE_ANALYSIS',
210
+ payload: { ...savedAnalysisData },
211
+ })
212
+ },
213
+ [dispatch]
214
+ )
215
+
216
+ const handleAudioEvent = useCallback(
217
+ async (eventData: AudioEventPayload) => {
218
+ const {
219
+ fileUri,
220
+ deltaSize,
221
+ totalSize,
222
+ lastEmittedSize,
223
+ position,
224
+ streamUuid,
225
+ encoded,
226
+ mimeType,
227
+ buffer,
228
+ } = eventData
229
+ logger.debug(`[handleAudioEvent] Received audio event:`, {
230
+ fileUri,
231
+ deltaSize,
232
+ totalSize,
233
+ position,
234
+ mimeType,
235
+ lastEmittedSize,
236
+ streamUuid,
237
+ encodedLength: encoded?.length,
238
+ })
239
+ if (deltaSize === 0) {
240
+ // Ignore packet with no data
241
+ return
242
+ }
243
+ try {
244
+ // Coming from native ( ios / android ) otherwise buffer is set
245
+ if (Platform.OS !== 'web') {
246
+ // Read the audio file as a base64 string for comparison
247
+ if (!encoded) {
248
+ console.error(`${TAG} Encoded audio data is missing`)
249
+ throw new Error('Encoded audio data is missing')
250
+ }
251
+ onAudioStreamRef.current?.({
252
+ data: encoded,
253
+ position,
254
+ fileUri,
255
+ eventDataSize: deltaSize,
256
+ totalSize,
257
+ })
258
+ } else if (buffer) {
259
+ // Coming from web
260
+ const webEvent: AudioDataEvent = {
261
+ data: buffer,
262
+ position,
263
+ fileUri,
264
+ eventDataSize: deltaSize,
265
+ totalSize,
266
+ }
267
+ onAudioStreamRef.current?.(webEvent)
268
+ logger.debug(
269
+ `[handleAudioEvent] Audio data sent to onAudioStream`,
270
+ webEvent
271
+ )
272
+ }
273
+ } catch (error) {
274
+ console.error(`${TAG} Error processing audio event:`, error)
275
+ }
276
+ },
277
+ []
278
+ )
279
+
280
+ const checkStatus = useCallback(async () => {
281
+ try {
282
+ if (!state.isRecording) {
283
+ logger.debug(`Not recording, exiting status check.`)
284
+ return
285
+ }
286
+
287
+ const status: AudioStreamStatus = ExpoAudioStream.status()
288
+ if (debug) {
289
+ logger.debug(`Status:`, status)
290
+ }
291
+
292
+ dispatch({
293
+ type: 'UPDATE_STATUS',
294
+ payload: { durationMs: status.durationMs, size: status.size },
295
+ })
296
+ } catch (error) {
297
+ console.error(`${TAG} Error getting status:`, error)
298
+ }
299
+ }, [state.isRecording])
300
+
301
+ const startRecording = useCallback(
302
+ async (recordingOptions: RecordingConfig) => {
303
+ logger.debug(`start recoding`, recordingOptions)
304
+
305
+ analysisRef.current = { ...defaultAnalysis } // Reset analysis data
306
+
307
+ const { onAudioStream, ...options } = recordingOptions
308
+ const { enableProcessing } = options
309
+
310
+ const maxRecentDataDuration = 10000 // TODO compute maxRecentDataDuration based on screen dimensions
311
+ if (typeof onAudioStream === 'function') {
312
+ onAudioStreamRef.current = onAudioStream
313
+ } else {
314
+ console.warn(
315
+ `${TAG} onAudioStream is not a function`,
316
+ onAudioStream
317
+ )
318
+ onAudioStreamRef.current = null
319
+ }
320
+ const startResult: StartRecordingResult =
321
+ await ExpoAudioStream.startRecording(options)
322
+ dispatch({ type: 'START' })
323
+
324
+ if (enableProcessing) {
325
+ logger.debug(`Enabling audio analysis listener`)
326
+ const listener = addAudioAnalysisListener(
327
+ async (analysisData) => {
328
+ try {
329
+ await handleAudioAnalysis({
330
+ analysis: analysisData,
331
+ visualizationDuration: maxRecentDataDuration,
332
+ })
333
+ } catch (error) {
334
+ console.warn(
335
+ `${TAG} Error processing audio analysis:`,
336
+ error
337
+ )
338
+ }
339
+ }
340
+ )
341
+
342
+ analysisListenerRef.current = listener
343
+ }
344
+
345
+ return startResult
346
+ },
347
+ [handleAudioAnalysis, dispatch]
348
+ )
349
+
350
+ const stopRecording = useCallback(async () => {
351
+ logger.debug(`stoping recording`)
352
+
353
+ const stopResult: AudioRecording = await ExpoAudioStream.stopRecording()
354
+ stopResult.analysisData = analysisRef.current
355
+
356
+ if (analysisListenerRef.current) {
357
+ analysisListenerRef.current.remove()
358
+ analysisListenerRef.current = null
359
+ }
360
+ onAudioStreamRef.current = null
361
+ logger.debug(`recording stopped`, stopResult)
362
+ dispatch({ type: 'STOP' })
363
+ return stopResult
364
+ }, [dispatch])
365
+
366
+ const pauseRecording = useCallback(async () => {
367
+ logger.debug(`pause recording`)
368
+ const pauseResult = await ExpoAudioStream.pauseRecording()
369
+ dispatch({ type: 'PAUSE' })
370
+ return pauseResult
371
+ }, [dispatch])
372
+
373
+ const resumeRecording = useCallback(async () => {
374
+ logger.debug(`resume recording`)
375
+ const resumeResult = await ExpoAudioStream.resumeRecording()
376
+ dispatch({ type: 'RESUME' })
377
+ return resumeResult
378
+ }, [dispatch])
379
+
380
+ useEffect(() => {
381
+ let interval: ReturnType<typeof setTimeout>
382
+ if (state.isRecording) {
383
+ interval = setInterval(checkStatus, 1000)
384
+ }
385
+ return () => {
386
+ if (interval) {
387
+ clearInterval(interval)
388
+ }
389
+ }
390
+ }, [checkStatus, state.isRecording])
391
+
392
+ useEffect(() => {
393
+ logger.debug(`Registering audio event listener`)
394
+ const subscribeAudio = addAudioEventListener(handleAudioEvent)
395
+
396
+ logger.debug(
397
+ `Subscribed to audio event listener and analysis listener`,
398
+ {
399
+ subscribeAudio,
400
+ }
401
+ )
402
+
403
+ return () => {
404
+ logger.debug(`Removing audio event listener`)
405
+ subscribeAudio.remove()
406
+ }
407
+ }, [handleAudioEvent, handleAudioAnalysis])
408
+
409
+ return {
410
+ startRecording,
411
+ stopRecording,
412
+ pauseRecording,
413
+ resumeRecording,
414
+ isPaused: state.isPaused,
415
+ isRecording: state.isRecording,
416
+ durationMs: state.durationMs,
417
+ size: state.size,
418
+ analysisData: state.analysisData,
419
+ }
420
+ }