@waveform-playlist/recording 5.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Naomi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,232 @@
1
+ # @waveform-playlist/recording
2
+
3
+ Audio recording support for waveform-playlist using AudioWorklet.
4
+
5
+ ## Features
6
+
7
+ - ✅ **AudioWorklet-based recording** - Low latency, direct PCM access
8
+ - ✅ **Real-time waveform visualization** - See the waveform as you record
9
+ - ✅ **React hooks** - Easy integration with React apps
10
+ - ✅ **Device selection** - Choose from available microphone inputs
11
+ - ✅ **Optional package** - Only include if you need recording
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @waveform-playlist/recording
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ### Basic Recording
22
+
23
+ ```typescript
24
+ import { useRecording, useMicrophoneAccess, RecordButton } from '@waveform-playlist/recording';
25
+
26
+ function RecordingApp() {
27
+ const { stream, requestAccess } = useMicrophoneAccess();
28
+ const { isRecording, startRecording, stopRecording, peaks, duration } = useRecording(stream);
29
+
30
+ const handleRecord = async () => {
31
+ if (!stream) {
32
+ await requestAccess();
33
+ }
34
+
35
+ if (isRecording) {
36
+ const audioBuffer = await stopRecording();
37
+ // Use the recorded audio buffer
38
+ } else {
39
+ await startRecording();
40
+ }
41
+ };
42
+
43
+ return (
44
+ <div>
45
+ <RecordButton isRecording={isRecording} onClick={handleRecord} />
46
+ <p>Duration: {duration.toFixed(1)}s</p>
47
+ {/* Display waveform using peaks */}
48
+ </div>
49
+ );
50
+ }
51
+ ```
52
+
53
+ ### With Microphone Selection
54
+
55
+ ```typescript
56
+ import {
57
+ useMicrophoneAccess,
58
+ useRecording,
59
+ MicrophoneSelector,
60
+ RecordButton,
61
+ RecordingIndicator,
62
+ } from '@waveform-playlist/recording';
63
+
64
+ function RecordingApp() {
65
+ const { stream, devices, requestAccess } = useMicrophoneAccess();
66
+ const { isRecording, duration, startRecording, stopRecording } = useRecording(stream);
67
+ const [selectedDevice, setSelectedDevice] = useState<string>();
68
+
69
+ const handleDeviceChange = async (deviceId: string) => {
70
+ setSelectedDevice(deviceId);
71
+ await requestAccess(deviceId);
72
+ };
73
+
74
+ return (
75
+ <div>
76
+ <MicrophoneSelector
77
+ devices={devices}
78
+ selectedDeviceId={selectedDevice}
79
+ onDeviceChange={handleDeviceChange}
80
+ />
81
+ <RecordButton
82
+ isRecording={isRecording}
83
+ onClick={isRecording ? stopRecording : startRecording}
84
+ />
85
+ <RecordingIndicator isRecording={isRecording} duration={duration} />
86
+ </div>
87
+ );
88
+ }
89
+ ```
90
+
91
+ ### Integration with WaveformPlaylist
92
+
93
+ ```typescript
94
+ import { WaveformPlaylistProvider, Waveform } from '@waveform-playlist/browser';
95
+ import { useRecording, useMicrophoneAccess } from '@waveform-playlist/recording';
96
+
97
+ function RecordingPlaylist() {
98
+ const { stream, requestAccess } = useMicrophoneAccess();
99
+ const { peaks, audioBuffer, startRecording, stopRecording } = useRecording(stream);
100
+ const [tracks, setTracks] = useState([]);
101
+
102
+ const handleStopRecording = async () => {
103
+ const buffer = await stopRecording();
104
+ if (buffer) {
105
+ // Add recorded track to playlist
106
+ setTracks([
107
+ ...tracks,
108
+ {
109
+ src: buffer,
110
+ name: 'Recording',
111
+ },
112
+ ]);
113
+ }
114
+ };
115
+
116
+ return (
117
+ <WaveformPlaylistProvider tracks={tracks}>
118
+ <button onClick={requestAccess}>Request Microphone</button>
119
+ <button onClick={startRecording}>Record</button>
120
+ <button onClick={handleStopRecording}>Stop</button>
121
+ <Waveform />
122
+ </WaveformPlaylistProvider>
123
+ );
124
+ }
125
+ ```
126
+
127
+ ## API Reference
128
+
129
+ ### Hooks
130
+
131
+ #### `useMicrophoneAccess()`
132
+
133
+ Manages microphone access and device enumeration.
134
+
135
+ **Returns:**
136
+ - `stream: MediaStream | null` - Active microphone stream
137
+ - `devices: MicrophoneDevice[]` - Available microphone devices
138
+ - `hasPermission: boolean` - Whether microphone permission is granted
139
+ - `isLoading: boolean` - Loading state during access request
140
+ - `requestAccess: (deviceId?: string) => Promise<void>` - Request microphone access
141
+ - `stopStream: () => void` - Stop the microphone stream
142
+ - `error: Error | null` - Error state
143
+
144
+ #### `useRecording(stream, options?)`
145
+
146
+ Main recording hook using AudioWorklet.
147
+
148
+ **Parameters:**
149
+ - `stream: MediaStream | null` - Microphone stream from `useMicrophoneAccess`
150
+ - `options?: RecordingOptions`
151
+ - `sampleRate?: number` - Sample rate (defaults to AudioContext rate)
152
+ - `channelCount?: number` - Number of channels (default: 1)
153
+ - `samplesPerPixel?: number` - Samples per pixel for peaks (default: 1024)
154
+
155
+ **Returns:**
156
+ - `isRecording: boolean` - Whether recording is active
157
+ - `isPaused: boolean` - Whether recording is paused
158
+ - `duration: number` - Recording duration in seconds
159
+ - `peaks: number[]` - Peak data for waveform visualization
160
+ - `audioBuffer: AudioBuffer | null` - Final recorded audio buffer
161
+ - `startRecording: () => Promise<void>` - Start recording
162
+ - `stopRecording: () => Promise<AudioBuffer | null>` - Stop and finalize recording
163
+ - `pauseRecording: () => void` - Pause recording
164
+ - `resumeRecording: () => void` - Resume recording
165
+ - `error: Error | null` - Error state
166
+
167
+ ### Components
168
+
169
+ #### `<RecordButton />`
170
+
171
+ Button for starting/stopping recording.
172
+
173
+ **Props:**
174
+ - `isRecording: boolean` - Recording state
175
+ - `onClick: () => void` - Click handler
176
+ - `disabled?: boolean` - Disabled state
177
+ - `className?: string` - CSS class name
178
+
179
+ #### `<MicrophoneSelector />`
180
+
181
+ Dropdown for selecting microphone device.
182
+
183
+ **Props:**
184
+ - `devices: MicrophoneDevice[]` - Available devices
185
+ - `selectedDeviceId?: string` - Currently selected device
186
+ - `onDeviceChange: (deviceId: string) => void` - Change handler
187
+ - `disabled?: boolean` - Disabled state
188
+ - `className?: string` - CSS class name
189
+
190
+ #### `<RecordingIndicator />`
191
+
192
+ Visual indicator showing recording status and duration.
193
+
194
+ **Props:**
195
+ - `isRecording: boolean` - Recording state
196
+ - `isPaused?: boolean` - Paused state
197
+ - `duration: number` - Duration in seconds
198
+ - `formatTime?: (seconds: number) => string` - Custom time formatter
199
+ - `className?: string` - CSS class name
200
+
201
+ ## Architecture
202
+
203
+ The recording implementation uses AudioWorklet for low-latency audio capture:
204
+
205
+ ```
206
+ getUserMedia → MediaStream
207
+
208
+ MediaStreamSource (Web Audio)
209
+
210
+ AudioWorklet Processor
211
+ (captures raw PCM data)
212
+
213
+ Main Thread (React Hook)
214
+ - Accumulates audio data
215
+ - Generates peaks in real-time
216
+ - Updates waveform visualization
217
+
218
+ Final AudioBuffer
219
+ ```
220
+
221
+ ## Browser Support
222
+
223
+ - Chrome 66+
224
+ - Firefox 76+
225
+ - Edge 79+
226
+ - Safari 14.1+
227
+
228
+ Requires HTTPS or localhost for microphone access.
229
+
230
+ ## License
231
+
232
+ MIT
@@ -0,0 +1,234 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * Types for the recording package
5
+ */
6
+ interface RecordingState {
7
+ isRecording: boolean;
8
+ isPaused: boolean;
9
+ duration: number;
10
+ sampleRate: number;
11
+ }
12
+ interface RecordingData {
13
+ buffer: AudioBuffer | null;
14
+ peaks: Int8Array | Int16Array;
15
+ duration: number;
16
+ }
17
+ interface MicrophoneDevice {
18
+ deviceId: string;
19
+ label: string;
20
+ groupId: string;
21
+ }
22
+ interface RecordingOptions {
23
+ /**
24
+ * Number of channels to record (1 = mono, 2 = stereo)
25
+ * Default: 1 (mono)
26
+ * Note: Sample rate is determined by the global AudioContext
27
+ */
28
+ channelCount?: number;
29
+ /**
30
+ * Samples per pixel for peak generation
31
+ * Default: 1024
32
+ */
33
+ samplesPerPixel?: number;
34
+ /**
35
+ * Specific device ID to use for recording
36
+ */
37
+ deviceId?: string;
38
+ /**
39
+ * MediaTrackConstraints for audio recording
40
+ * Use this to customize echo cancellation, noise suppression, auto gain control, latency, etc.
41
+ * Default: Recording-optimized settings (all processing disabled, latency: 0 for low latency)
42
+ */
43
+ audioConstraints?: MediaTrackConstraints;
44
+ }
45
+ interface UseRecordingReturn {
46
+ isRecording: boolean;
47
+ isPaused: boolean;
48
+ duration: number;
49
+ peaks: Int8Array | Int16Array;
50
+ audioBuffer: AudioBuffer | null;
51
+ level: number;
52
+ peakLevel: number;
53
+ startRecording: () => Promise<void>;
54
+ stopRecording: () => Promise<AudioBuffer | null>;
55
+ pauseRecording: () => void;
56
+ resumeRecording: () => void;
57
+ error: Error | null;
58
+ }
59
+ interface UseMicrophoneAccessReturn {
60
+ stream: MediaStream | null;
61
+ devices: MicrophoneDevice[];
62
+ hasPermission: boolean;
63
+ isLoading: boolean;
64
+ requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>;
65
+ stopStream: () => void;
66
+ error: Error | null;
67
+ }
68
+
69
+ /**
70
+ * Main recording hook using AudioWorklet
71
+ */
72
+
73
+ declare function useRecording(stream: MediaStream | null, options?: RecordingOptions): UseRecordingReturn;
74
+
75
+ /**
76
+ * Hook for managing microphone access and device enumeration
77
+ */
78
+
79
+ declare function useMicrophoneAccess(): UseMicrophoneAccessReturn;
80
+
81
+ /**
82
+ * Hook for monitoring microphone input levels
83
+ *
84
+ * Uses Tone.js Meter for real-time audio level monitoring.
85
+ */
86
+ interface UseMicrophoneLevelOptions {
87
+ /**
88
+ * How often to update the level (in Hz)
89
+ * Default: 60 (60fps)
90
+ */
91
+ updateRate?: number;
92
+ /**
93
+ * FFT size for the analyser
94
+ * Default: 256
95
+ */
96
+ fftSize?: number;
97
+ /**
98
+ * Smoothing time constant (0-1)
99
+ * Higher values = smoother but slower response
100
+ * Default: 0.8
101
+ */
102
+ smoothingTimeConstant?: number;
103
+ }
104
+ interface UseMicrophoneLevelReturn {
105
+ /**
106
+ * Current audio level (0-1)
107
+ * 0 = silence, 1 = maximum level
108
+ */
109
+ level: number;
110
+ /**
111
+ * Peak level since last reset (0-1)
112
+ */
113
+ peakLevel: number;
114
+ /**
115
+ * Reset the peak level
116
+ */
117
+ resetPeak: () => void;
118
+ }
119
+ /**
120
+ * Monitor microphone input levels in real-time
121
+ *
122
+ * @param stream - MediaStream from getUserMedia
123
+ * @param options - Configuration options
124
+ * @returns Object with current level and peak level
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * const { stream } = useMicrophoneAccess();
129
+ * const { level, peakLevel, resetPeak } = useMicrophoneLevel(stream);
130
+ *
131
+ * return <VUMeter level={level} peakLevel={peakLevel} />;
132
+ * ```
133
+ */
134
+ declare function useMicrophoneLevel(stream: MediaStream | null, options?: UseMicrophoneLevelOptions): UseMicrophoneLevelReturn;
135
+
136
+ /**
137
+ * RecordButton - Control button for starting/stopping recording
138
+ */
139
+
140
+ interface RecordButtonProps {
141
+ isRecording: boolean;
142
+ onClick: () => void;
143
+ disabled?: boolean;
144
+ className?: string;
145
+ }
146
+ declare const RecordButton: React.FC<RecordButtonProps>;
147
+
148
+ /**
149
+ * MicrophoneSelector - Dropdown for selecting microphone input device
150
+ */
151
+
152
+ interface MicrophoneSelectorProps {
153
+ devices: MicrophoneDevice[];
154
+ selectedDeviceId?: string;
155
+ onDeviceChange: (deviceId: string) => void;
156
+ disabled?: boolean;
157
+ className?: string;
158
+ }
159
+ declare const MicrophoneSelector: React.FC<MicrophoneSelectorProps>;
160
+
161
+ /**
162
+ * RecordingIndicator - Shows recording status, duration, and visual indicator
163
+ */
164
+
165
+ interface RecordingIndicatorProps {
166
+ isRecording: boolean;
167
+ isPaused?: boolean;
168
+ duration: number;
169
+ formatTime?: (seconds: number) => string;
170
+ className?: string;
171
+ }
172
+ declare const RecordingIndicator: React.FC<RecordingIndicatorProps>;
173
+
174
+ /**
175
+ * VU Meter Component
176
+ *
177
+ * Displays real-time audio input levels with color-coded zones
178
+ * and peak indicator.
179
+ */
180
+
181
+ interface VUMeterProps {
182
+ /**
183
+ * Current audio level (0-1)
184
+ */
185
+ level: number;
186
+ /**
187
+ * Peak level (0-1)
188
+ * Optional - if provided, shows peak indicator
189
+ */
190
+ peakLevel?: number;
191
+ /**
192
+ * Width of the meter in pixels
193
+ * Default: 200
194
+ */
195
+ width?: number;
196
+ /**
197
+ * Height of the meter in pixels
198
+ * Default: 20
199
+ */
200
+ height?: number;
201
+ /**
202
+ * Additional CSS class name
203
+ */
204
+ className?: string;
205
+ }
206
+ declare const VUMeter: React.NamedExoticComponent<VUMeterProps>;
207
+
208
+ /**
209
+ * Peak generation for real-time waveform visualization during recording
210
+ * Matches the format used by webaudio-peaks: min/max pairs with bit depth
211
+ */
212
+ /**
213
+ * Generate peaks from audio samples in standard min/max pair format
214
+ *
215
+ * @param samples - Audio samples to process
216
+ * @param samplesPerPixel - Number of samples to represent in each peak
217
+ * @param bits - Bit depth for peak values (8 or 16)
218
+ * @returns Int8Array or Int16Array of peak values (min/max pairs)
219
+ */
220
+ declare function generatePeaks(samples: Float32Array, samplesPerPixel: number, bits?: 8 | 16): Int8Array | Int16Array;
221
+
222
+ /**
223
+ * Utility functions for working with AudioBuffers during recording
224
+ */
225
+ /**
226
+ * Concatenate multiple Float32Arrays into a single array
227
+ */
228
+ declare function concatenateAudioData(chunks: Float32Array[]): Float32Array;
229
+ /**
230
+ * Convert Float32Array to AudioBuffer
231
+ */
232
+ declare function createAudioBuffer(audioContext: AudioContext, samples: Float32Array, sampleRate: number, channelCount?: number): AudioBuffer;
233
+
234
+ export { type MicrophoneDevice, MicrophoneSelector, type MicrophoneSelectorProps, RecordButton, type RecordButtonProps, type RecordingData, RecordingIndicator, type RecordingIndicatorProps, type RecordingOptions, type RecordingState, type UseMicrophoneAccessReturn, type UseMicrophoneLevelOptions, type UseMicrophoneLevelReturn, type UseRecordingReturn, VUMeter, type VUMeterProps, concatenateAudioData, createAudioBuffer, generatePeaks, useMicrophoneAccess, useMicrophoneLevel, useRecording };