@siteed/expo-audio-stream 1.1.2 → 1.1.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 (105) hide show
  1. package/build/AudioAnalysis/AudioAnalysis.types.d.ts +74 -0
  2. package/build/AudioAnalysis/AudioAnalysis.types.d.ts.map +1 -0
  3. package/build/AudioAnalysis/AudioAnalysis.types.js +3 -0
  4. package/build/AudioAnalysis/AudioAnalysis.types.js.map +1 -0
  5. package/build/AudioAnalysis/extractAudioAnalysis.d.ts +20 -0
  6. package/build/AudioAnalysis/extractAudioAnalysis.d.ts.map +1 -0
  7. package/build/AudioAnalysis/extractAudioAnalysis.js +88 -0
  8. package/build/AudioAnalysis/extractAudioAnalysis.js.map +1 -0
  9. package/build/AudioAnalysis/extractWaveform.d.ts +8 -0
  10. package/build/AudioAnalysis/extractWaveform.d.ts.map +1 -0
  11. package/build/AudioAnalysis/extractWaveform.js +14 -0
  12. package/build/AudioAnalysis/extractWaveform.js.map +1 -0
  13. package/build/AudioRecorder.provider.d.ts +23 -0
  14. package/build/AudioRecorder.provider.d.ts.map +1 -0
  15. package/build/AudioRecorder.provider.js +36 -0
  16. package/build/AudioRecorder.provider.js.map +1 -0
  17. package/build/ExpoAudioStream.native.d.ts +3 -0
  18. package/build/ExpoAudioStream.native.d.ts.map +1 -0
  19. package/{src/ExpoAudioStream.native.ts → build/ExpoAudioStream.native.js} +3 -3
  20. package/build/ExpoAudioStream.native.js.map +1 -0
  21. package/build/ExpoAudioStream.types.d.ts +65 -0
  22. package/build/ExpoAudioStream.types.d.ts.map +1 -0
  23. package/build/ExpoAudioStream.types.js +2 -0
  24. package/build/ExpoAudioStream.types.js.map +1 -0
  25. package/build/ExpoAudioStream.web.d.ts +42 -0
  26. package/build/ExpoAudioStream.web.d.ts.map +1 -0
  27. package/build/ExpoAudioStream.web.js +203 -0
  28. package/build/ExpoAudioStream.web.js.map +1 -0
  29. package/build/ExpoAudioStreamModule.d.ts +3 -0
  30. package/build/ExpoAudioStreamModule.d.ts.map +1 -0
  31. package/build/ExpoAudioStreamModule.js +25 -0
  32. package/build/ExpoAudioStreamModule.js.map +1 -0
  33. package/build/WebRecorder.web.d.ts +51 -0
  34. package/build/WebRecorder.web.d.ts.map +1 -0
  35. package/build/WebRecorder.web.js +298 -0
  36. package/build/WebRecorder.web.js.map +1 -0
  37. package/build/constants.d.ts +11 -0
  38. package/build/constants.d.ts.map +1 -0
  39. package/build/constants.js +14 -0
  40. package/build/constants.js.map +1 -0
  41. package/build/events.d.ts +18 -0
  42. package/build/events.d.ts.map +1 -0
  43. package/build/events.js +15 -0
  44. package/build/events.js.map +1 -0
  45. package/build/index.d.ts +11 -0
  46. package/build/index.d.ts.map +1 -0
  47. package/build/index.js.map +1 -0
  48. package/build/logger.d.ts +9 -0
  49. package/build/logger.d.ts.map +1 -0
  50. package/build/logger.js +13 -0
  51. package/build/logger.js.map +1 -0
  52. package/build/useAudioRecorder.d.ts +20 -0
  53. package/build/useAudioRecorder.d.ts.map +1 -0
  54. package/build/useAudioRecorder.js +271 -0
  55. package/build/useAudioRecorder.js.map +1 -0
  56. package/build/utils/BlobFix.d.ts +9 -0
  57. package/build/utils/BlobFix.d.ts.map +1 -0
  58. package/{src/utils/BlobFix.ts → build/utils/BlobFix.js} +66 -122
  59. package/build/utils/BlobFix.js.map +1 -0
  60. package/build/utils/concatenateBuffers.d.ts +8 -0
  61. package/build/utils/concatenateBuffers.d.ts.map +1 -0
  62. package/{src/utils/concatenateBuffers.ts → build/utils/concatenateBuffers.js} +10 -13
  63. package/build/utils/concatenateBuffers.js.map +1 -0
  64. package/build/utils/convertPCMToFloat32.d.ts +11 -0
  65. package/build/utils/convertPCMToFloat32.d.ts.map +1 -0
  66. package/build/utils/convertPCMToFloat32.js +54 -0
  67. package/build/utils/convertPCMToFloat32.js.map +1 -0
  68. package/build/utils/encodingToBitDepth.d.ts +5 -0
  69. package/build/utils/encodingToBitDepth.d.ts.map +1 -0
  70. package/build/utils/encodingToBitDepth.js +13 -0
  71. package/build/utils/encodingToBitDepth.js.map +1 -0
  72. package/build/utils/getWavFileInfo.d.ts +26 -0
  73. package/build/utils/getWavFileInfo.d.ts.map +1 -0
  74. package/build/utils/getWavFileInfo.js +92 -0
  75. package/build/utils/getWavFileInfo.js.map +1 -0
  76. package/build/utils/writeWavHeader.d.ts +9 -0
  77. package/build/utils/writeWavHeader.d.ts.map +1 -0
  78. package/build/utils/writeWavHeader.js +45 -0
  79. package/build/utils/writeWavHeader.js.map +1 -0
  80. package/build/workers/InlineFeaturesExtractor.web.d.ts +2 -0
  81. package/build/workers/InlineFeaturesExtractor.web.d.ts.map +1 -0
  82. package/{src/workers/InlineFeaturesExtractor.web.tsx → build/workers/InlineFeaturesExtractor.web.js} +2 -1
  83. package/build/workers/InlineFeaturesExtractor.web.js.map +1 -0
  84. package/build/workers/inlineAudioWebWorker.web.d.ts +2 -0
  85. package/build/workers/inlineAudioWebWorker.web.d.ts.map +1 -0
  86. package/{src/workers/inlineAudioWebWorker.web.tsx → build/workers/inlineAudioWebWorker.web.js} +2 -1
  87. package/build/workers/inlineAudioWebWorker.web.js.map +1 -0
  88. package/package.json +2 -2
  89. package/src/AudioAnalysis/AudioAnalysis.types.ts +0 -84
  90. package/src/AudioAnalysis/extractAudioAnalysis.ts +0 -147
  91. package/src/AudioAnalysis/extractWaveform.ts +0 -25
  92. package/src/AudioRecorder.provider.tsx +0 -70
  93. package/src/ExpoAudioStream.types.ts +0 -80
  94. package/src/ExpoAudioStream.web.ts +0 -255
  95. package/src/ExpoAudioStreamModule.ts +0 -31
  96. package/src/WebRecorder.web.ts +0 -433
  97. package/src/constants.ts +0 -18
  98. package/src/events.ts +0 -39
  99. package/src/index.ts +0 -24
  100. package/src/logger.ts +0 -22
  101. package/src/useAudioRecorder.tsx +0 -420
  102. package/src/utils/convertPCMToFloat32.ts +0 -75
  103. package/src/utils/encodingToBitDepth.ts +0 -18
  104. package/src/utils/getWavFileInfo.ts +0 -132
  105. package/src/utils/writeWavHeader.ts +0 -61
@@ -1,420 +0,0 @@
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
- }
@@ -1,75 +0,0 @@
1
- import { getWavFileInfo, WavFileInfo } from './getWavFileInfo'
2
- import { getLogger } from '../logger'
3
-
4
- export const WAV_HEADER_SIZE = 44
5
-
6
- const logger = getLogger('convertPCMToFloat32')
7
-
8
- const convertSample = (
9
- dataView: DataView,
10
- offset: number,
11
- bitDepth: number
12
- ): number => {
13
- switch (bitDepth) {
14
- case 8:
15
- return (dataView.getUint8(offset) - 128) / 128
16
- case 16:
17
- return dataView.getInt16(offset, true) / 32768
18
- case 24:
19
- return (
20
- ((dataView.getUint8(offset) |
21
- (dataView.getUint8(offset + 1) << 8) |
22
- (dataView.getUint8(offset + 2) << 16)) /
23
- 8388608) *
24
- 2 -
25
- 1
26
- )
27
- case 32:
28
- return dataView.getFloat32(offset, true)
29
- default:
30
- throw new Error(`Unsupported bit depth: ${bitDepth}`)
31
- }
32
- }
33
-
34
- export const convertPCMToFloat32 = async ({
35
- bitDepth,
36
- buffer,
37
- skipWavHeader = false,
38
- }: {
39
- buffer: ArrayBuffer
40
- bitDepth: number
41
- skipWavHeader?: boolean
42
- }): Promise<{ pcmValues: Float32Array; min: number; max: number }> => {
43
- try {
44
- logger.debug(
45
- `Converting PCM to Float32: bitDepth: ${bitDepth}, buffer.byteLength: ${buffer.byteLength}`
46
- )
47
- const dataView = new DataView(buffer)
48
- let headerOffset = 0
49
- if (skipWavHeader) {
50
- const wavFileInfo: WavFileInfo = await getWavFileInfo(buffer)
51
- headerOffset = wavFileInfo.dataChunkOffset
52
- }
53
-
54
- const dataLength = buffer.byteLength - headerOffset
55
- const sampleLength = Math.floor(dataLength / (bitDepth / 8))
56
- const float32Array = new Float32Array(sampleLength)
57
- let min = Infinity
58
- let max = -Infinity
59
-
60
- for (let i = 0; i < sampleLength; i++) {
61
- const offset = headerOffset + i * (bitDepth / 8)
62
- const value = convertSample(dataView, offset, bitDepth)
63
-
64
- if (value < min) min = value
65
- if (value > max) max = value
66
-
67
- float32Array[i] = value
68
- }
69
-
70
- return { pcmValues: float32Array, min, max }
71
- } catch (error: unknown) {
72
- logger.error(`Error converting PCM to Float32`, error)
73
- return { pcmValues: new Float32Array(), min: 0, max: 0 }
74
- }
75
- }
@@ -1,18 +0,0 @@
1
- import { BitDepth, EncodingType } from '../ExpoAudioStream.types'
2
-
3
- export const encodingToBitDepth = ({
4
- encoding,
5
- }: {
6
- encoding: EncodingType
7
- }): BitDepth => {
8
- switch (encoding) {
9
- case 'pcm_32bit':
10
- return 32
11
- case 'pcm_16bit':
12
- return 16
13
- case 'pcm_8bit':
14
- return 8
15
- default:
16
- throw new Error(`Unsupported encoding type: ${encoding}`)
17
- }
18
- }
@@ -1,132 +0,0 @@
1
- // packages/expo-audio-stream/src/utils/getWavFileInfo.ts
2
-
3
- import { BitDepth, SampleRate } from '../ExpoAudioStream.types'
4
- import {
5
- DATA_CHUNK_ID,
6
- DEFAULT_BIT_DEPTH,
7
- DEFAULT_SAMPLE_RATE,
8
- FMT_CHUNK_ID,
9
- INFO_CHUNK_ID,
10
- RIFF_HEADER,
11
- WAVE_HEADER,
12
- } from '../constants'
13
-
14
- // Audio format descriptions
15
- const AUDIO_FORMATS: { [key: number]: string } = {
16
- 1: 'PCM',
17
- 3: 'IEEE float',
18
- 6: '8-bit ITU-T G.711 A-law',
19
- 7: '8-bit ITU-T G.711 µ-law',
20
- 65534: 'WAVE_FORMAT_EXTENSIBLE',
21
- }
22
-
23
- /**
24
- * Interface representing the metadata of a WAV file.
25
- */
26
- export interface WavFileInfo {
27
- sampleRate: SampleRate
28
- numChannels: number
29
- bitDepth: BitDepth
30
- size: number // in bytes
31
- durationMs: number // in ms
32
- audioFormatDescription: string // Description of the audio format
33
- byteRate: number // Average bytes per second
34
- blockAlign: number // Number of bytes for one sample including all channels
35
- creationDateTime?: string // Optional creation date and time
36
- comments?: string // Optional comments or tags
37
- compressionType?: string // Optional compression type
38
- dataChunkOffset: number // Position of the first data chunk
39
- }
40
-
41
- /**
42
- * Extracts metadata from a WAV buffer.
43
- *
44
- * @param arrayBuffer - The array buffer containing the WAV data.
45
- * @returns A promise that resolves to the extracted metadata.
46
- */
47
- export const getWavFileInfo = async (
48
- arrayBuffer: ArrayBuffer
49
- ): Promise<WavFileInfo> => {
50
- const view = new DataView(arrayBuffer)
51
-
52
- // Check if the file is a valid RIFF/WAVE file
53
- const riffHeader = view.getUint32(0, false)
54
- const waveHeader = view.getUint32(8, false)
55
- if (riffHeader !== RIFF_HEADER || waveHeader !== WAVE_HEADER) {
56
- throw new Error('Invalid WAV file')
57
- }
58
-
59
- // Initialize variables for the metadata
60
- let fmtChunkOffset = 12
61
- let sampleRate: SampleRate = DEFAULT_SAMPLE_RATE
62
- let numChannels = 0
63
- let bitDepth: BitDepth = DEFAULT_BIT_DEPTH
64
- let dataChunkSize = 0
65
- let audioFormat = 0
66
- let byteRate = 0
67
- let blockAlign = 0
68
- let creationDateTime = ''
69
- let comments = ''
70
- let dataChunkOffset = 0
71
-
72
- // Parse chunks to find the "fmt " and "data" chunks
73
- while (fmtChunkOffset < view.byteLength) {
74
- const chunkId = view.getUint32(fmtChunkOffset, false)
75
- const chunkSize = view.getUint32(fmtChunkOffset + 4, true)
76
- if (chunkId === FMT_CHUNK_ID) {
77
- // "fmt "
78
- audioFormat = view.getUint16(fmtChunkOffset + 8, true)
79
- if (!AUDIO_FORMATS[audioFormat]) {
80
- throw new Error('Unsupported WAV file format')
81
- }
82
- numChannels = view.getUint16(fmtChunkOffset + 10, true)
83
- sampleRate = view.getUint32(fmtChunkOffset + 12, true) as SampleRate
84
- byteRate = view.getUint32(fmtChunkOffset + 16, true)
85
- blockAlign = view.getUint16(fmtChunkOffset + 20, true)
86
- bitDepth = view.getUint16(fmtChunkOffset + 22, true) as BitDepth
87
- } else if (chunkId === DATA_CHUNK_ID) {
88
- // "data"
89
- dataChunkSize = chunkSize
90
- dataChunkOffset = fmtChunkOffset + 8 // Position after chunk header
91
- break
92
- } else if (chunkId === INFO_CHUNK_ID) {
93
- // "INFO"
94
- // Read INFO chunk (assuming it contains a text-based creation date/time and comments)
95
- const infoStart = fmtChunkOffset + 8
96
- const infoText = new TextDecoder().decode(
97
- new Uint8Array(
98
- arrayBuffer.slice(infoStart, infoStart + chunkSize)
99
- )
100
- )
101
- const infoParts = infoText.split('\0')
102
- creationDateTime = infoParts[0]
103
- comments = infoParts[1]
104
- }
105
- fmtChunkOffset += 8 + chunkSize
106
- }
107
-
108
- if (!sampleRate || !numChannels || !bitDepth || !dataChunkSize) {
109
- throw new Error('Incomplete WAV file information')
110
- }
111
-
112
- // Calculate duration
113
- const bytesPerSample = bitDepth / 8
114
- const numSamples = dataChunkSize / (numChannels * bytesPerSample)
115
- const durationMs = (numSamples / sampleRate) * 1000
116
-
117
- return {
118
- sampleRate,
119
- numChannels,
120
- bitDepth,
121
- size: arrayBuffer.byteLength,
122
- durationMs,
123
- audioFormatDescription: AUDIO_FORMATS[audioFormat],
124
- byteRate,
125
- blockAlign,
126
- creationDateTime: creationDateTime || undefined,
127
- comments: comments || undefined,
128
- compressionType:
129
- audioFormat === 1 ? 'None' : AUDIO_FORMATS[audioFormat],
130
- dataChunkOffset,
131
- }
132
- }
@@ -1,61 +0,0 @@
1
- // packages/expo-audio-stream/src/utils/writeWavHeader.ts
2
- interface WavHeaderOptions {
3
- buffer: ArrayBuffer
4
- sampleRate: number
5
- numChannels: number
6
- bitDepth: number
7
- }
8
-
9
- export const writeWavHeader = ({
10
- buffer,
11
- sampleRate,
12
- numChannels,
13
- bitDepth,
14
- }: WavHeaderOptions): ArrayBuffer => {
15
- const bytesPerSample = bitDepth / 8
16
- const numSamples = buffer.byteLength / (numChannels * bytesPerSample)
17
- const view = new DataView(buffer)
18
- const blockAlign = numChannels * bytesPerSample
19
- const byteRate = sampleRate * blockAlign
20
-
21
- // Function to write a string to the DataView
22
- const writeString = (view: DataView, offset: number, string: string) => {
23
- for (let i = 0; i < string.length; i++) {
24
- view.setUint8(offset + i, string.charCodeAt(i))
25
- }
26
- }
27
-
28
- // Check if the buffer already has a WAV header by looking for "RIFF" at the start
29
- const existingHeader = view.getUint32(0, false) === 0x52494646 // "RIFF" in ASCII
30
-
31
- if (!existingHeader) {
32
- // Ensure the buffer is large enough for the WAV header
33
- if (buffer.byteLength < 44) {
34
- throw new Error('Buffer is too small to contain a valid WAV header')
35
- }
36
-
37
- // Write the WAV header
38
- writeString(view, 0, 'RIFF') // ChunkID
39
- view.setUint32(4, 36 + numSamples * blockAlign, true) // ChunkSize
40
- writeString(view, 8, 'WAVE') // Format
41
- writeString(view, 12, 'fmt ') // Subchunk1ID
42
- view.setUint32(16, 16, true) // Subchunk1Size (16 for PCM)
43
- view.setUint16(20, bitDepth === 32 ? 3 : 1, true) // AudioFormat (3 for float, 1 for PCM)
44
- view.setUint16(22, numChannels, true) // NumChannels
45
- view.setUint32(24, sampleRate, true) // SampleRate
46
- view.setUint32(28, byteRate, true) // ByteRate
47
- view.setUint16(32, blockAlign, true) // BlockAlign
48
- view.setUint16(34, bitDepth, true) // BitsPerSample
49
- writeString(view, 36, 'data') // Subchunk2ID
50
- view.setUint32(40, numSamples * blockAlign, true) // Subchunk2Size
51
- } else {
52
- // Update the existing WAV header if necessary
53
- view.setUint32(4, 36 + numSamples * blockAlign, true) // Update ChunkSize
54
- view.setUint32(24, sampleRate, true) // Update SampleRate
55
- view.setUint32(28, byteRate, true) // Update ByteRate
56
- view.setUint16(32, blockAlign, true) // Update BlockAlign
57
- view.setUint32(40, numSamples * blockAlign, true) // Update Subchunk2Size
58
- }
59
-
60
- return buffer
61
- }