@waveform-playlist/recording 14.0.0-next.17 → 14.0.0-next.19
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/README.md +5 -4
- package/dist/index.d.mts +33 -24
- package/dist/index.d.ts +33 -24
- package/dist/index.js +145 -57
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +146 -58
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ Audio recording support for waveform-playlist using AudioWorklet — mic capture
|
|
|
9
9
|
- **Sample-accurate VU metering** — a dedicated meter worklet measures peak/RMS on every sample, not just once per animation frame
|
|
10
10
|
- **Multi-channel recording** — auto-detects the microphone's actual channel count from the `MediaStream`
|
|
11
11
|
- **Overdub with latency compensation** — record against existing playback; the finalized clip's timeline position accounts for output latency and Tone.js scheduling lookahead, with an optional manual override
|
|
12
|
-
- **Device selection & hot-plug** — enumerate microphones, switch devices between takes (refused while actively recording — a mid-recording switch would silently record silence),
|
|
12
|
+
- **Device selection & hot-plug** — enumerate microphones, switch devices between takes (refused while actively recording — a mid-recording switch would silently record silence), no microphone is opened by the hooks themselves: when the open one is unplugged, `stream` is cleared and the app asks again
|
|
13
13
|
- **Pause/resume** — pauses the worklet itself, not just the UI
|
|
14
14
|
- **Hooks only** — no bundled UI components; wire the state into your own controls or `@waveform-playlist/ui-components`'s `SegmentedVUMeter`
|
|
15
15
|
|
|
@@ -166,6 +166,7 @@ Manages microphone permission, device enumeration, and hot-plug detection.
|
|
|
166
166
|
**Returns (`UseMicrophoneAccessReturn`):**
|
|
167
167
|
- `stream: MediaStream | null`
|
|
168
168
|
- `devices: MicrophoneDevice[]` — `{ deviceId, label, groupId }`
|
|
169
|
+
- `hasLabels: boolean` — `devices` names the real microphones. Browsers hide them until microphone permission is granted (usually one entry with an empty `deviceId`). In our runs (headless, fake devices) Chromium holding the permission named them before any stream was open, so a picker can offer them and `requestAccess(deviceId)` opens only the one chosen; Firefox and WebKit named them only once a stream was open
|
|
169
170
|
- `hasPermission: boolean`
|
|
170
171
|
- `isLoading: boolean`
|
|
171
172
|
- `requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>`
|
|
@@ -188,7 +189,7 @@ The core AudioWorklet-based recording hook.
|
|
|
188
189
|
**Returns (`UseRecordingReturn`):**
|
|
189
190
|
- `isRecording: boolean`, `isPaused: boolean`
|
|
190
191
|
- `progress: RecordingProgressSource` — a source of `{ duration: number; peaks: (Int8Array | Int16Array)[] }` (seconds elapsed; one peaks entry per channel, growing live). Published once per animation frame while recording; the hook does not re-render for it. After a stop, `duration` is the recorded buffer's length
|
|
191
|
-
- `audioBuffer: AudioBuffer | null` — set after `stopRecording()` resolves
|
|
192
|
+
- `audioBuffer: AudioBuffer | null` — set after `stopRecording()` resolves, and when a take ends by itself (microphone unplugged, component hidden mid-take)
|
|
192
193
|
- `startRecording: () => Promise<boolean>` — resolves `true` when the capture pipeline actually started (`false`: no stream, already recording, worklet failure); check it before starting synchronized playback
|
|
193
194
|
- `stopRecording: () => Promise<AudioBuffer | null>` — awaits the worklet's final flush before resolving, so the last samples are never dropped
|
|
194
195
|
- `pauseRecording: () => void`, `resumeRecording: () => void` — pause/resume the worklet itself, not just the UI
|
|
@@ -226,13 +227,13 @@ Batteries-included hook: wires `useMicrophoneAccess` + `useMicrophoneLevel` + `u
|
|
|
226
227
|
- `samplesPerPixel?: number` (default: `1024`)
|
|
227
228
|
- `latencyOffset?: number` — seconds; overrides the auto-computed `outputLatency + lookAhead` compensation applied to the clip's start. `0` disables compensation; omit to auto-compute
|
|
228
229
|
|
|
229
|
-
**Returns (`UseIntegratedRecordingReturn`):** recording state (`isRecording`, `isPaused`, `recordingTrackId`: the track the running take was started on, `null` when none is running), the two live sources (`meter`: microphone levels; `progress`: the take's elapsed time and per-channel preview peaks), microphone state (`stream`, `devices`, `hasPermission`, `selectedDevice`), controls (`startRecording` — resolves `true` when capture actually started, `false` with `error` set when the take is refused, `stopRecording`, `pauseRecording`, `resumeRecording`, `requestMicAccess`, `changeDevice`), and a combined `error`.
|
|
230
|
+
**Returns (`UseIntegratedRecordingReturn`):** recording state (`isRecording`, `isPaused`, `recordingTrackId`: the track the running take was started on, `null` when none is running), the two live sources (`meter`: microphone levels; `progress`: the take's elapsed time and per-channel preview peaks), microphone state (`stream`, `devices`, `hasLabels`, `hasPermission`, and `selectedDevice`: the id the open stream reports, `null` while no microphone is open; `'default'` in Chromium for the default microphone), controls (`startRecording` — resolves `true` when capture actually started, `false` with `error` set when the take is refused, `stopRecording`, `pauseRecording`, `resumeRecording`, `requestMicAccess`, `changeDevice`), and a combined `error`.
|
|
230
231
|
|
|
231
232
|
**Recording into a `@waveform-playlist/browser` playlist:** call `useRecordingSession({ isRecording, trackId: recordingTrackId })` (from `@waveform-playlist/browser`) in the component that calls `useIntegratedRecording`; the view's `<WaveformRecordingPreview>` only draws the take. For an overdub, also call `useEditorControls().setRecordingActive(true, trackId)` *before* `play()` — while the session is active the end-of-timeline auto-stop is suppressed (the take can run past existing audio) and the recorded-over track plays muted for the take (punch-in replaces what it holds; `arrangement.setTrackRecording`, which leaves the track's own mute in the arrangement's mix alone): the mixer and the track's Mute button show it, the built-in `<TrackMuteButton />` is disabled, and `useTrack().isRecording` is true for it. A mute set on the track during the take stays after it. Both reset automatically when the recording ends; check `startRecording()`'s boolean and release the session on `false`. `play()` does nothing before the playlist's first ready, so a take started during the first load records without playback.
|
|
232
233
|
|
|
233
234
|
### Types
|
|
234
235
|
|
|
235
|
-
`
|
|
236
|
+
`MicrophoneDevice`, `RecordingOptions`, `UseRecordingReturn`, `UseMicrophoneAccessReturn` are all exported from the package root for consumers building their own UI around these hooks.
|
|
236
237
|
|
|
237
238
|
## Architecture
|
|
238
239
|
|
package/dist/index.d.mts
CHANGED
|
@@ -6,17 +6,6 @@ import { UseThrottledValueOptions } from '@waveform-playlist/ui-components';
|
|
|
6
6
|
* Types for the recording package
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
interface RecordingState {
|
|
10
|
-
isRecording: boolean;
|
|
11
|
-
isPaused: boolean;
|
|
12
|
-
duration: number;
|
|
13
|
-
sampleRate: number;
|
|
14
|
-
}
|
|
15
|
-
interface RecordingData {
|
|
16
|
-
buffer: AudioBuffer | null;
|
|
17
|
-
peaks: (Int8Array | Int16Array)[];
|
|
18
|
-
duration: number;
|
|
19
|
-
}
|
|
20
9
|
interface MicrophoneDevice {
|
|
21
10
|
deviceId: string;
|
|
22
11
|
label: string;
|
|
@@ -41,16 +30,6 @@ interface RecordingOptions {
|
|
|
41
30
|
* Default: 16
|
|
42
31
|
*/
|
|
43
32
|
bits?: 8 | 16;
|
|
44
|
-
/**
|
|
45
|
-
* Specific device ID to use for recording
|
|
46
|
-
*/
|
|
47
|
-
deviceId?: string;
|
|
48
|
-
/**
|
|
49
|
-
* MediaTrackConstraints for audio recording
|
|
50
|
-
* Use this to customize echo cancellation, noise suppression, auto gain control, latency, etc.
|
|
51
|
-
* Default: Recording-optimized settings (all processing disabled, latency: 0 for low latency)
|
|
52
|
-
*/
|
|
53
|
-
audioConstraints?: MediaTrackConstraints;
|
|
54
33
|
}
|
|
55
34
|
interface UseRecordingReturn {
|
|
56
35
|
isRecording: boolean;
|
|
@@ -79,6 +58,17 @@ interface UseRecordingReturn {
|
|
|
79
58
|
interface UseMicrophoneAccessReturn {
|
|
80
59
|
stream: MediaStream | null;
|
|
81
60
|
devices: MicrophoneDevice[];
|
|
61
|
+
/**
|
|
62
|
+
* True when `devices` names the real microphones, with their ids and
|
|
63
|
+
* labels. Browsers hide them until microphone permission is granted (the
|
|
64
|
+
* list is then usually one entry with an empty `deviceId`). Chromium holding
|
|
65
|
+
* the permission listed them before any stream was open (headless runs with
|
|
66
|
+
* fake devices), so a picker can offer them and open only the one chosen,
|
|
67
|
+
* with `requestAccess(deviceId)`; Firefox and WebKit listed them only once a
|
|
68
|
+
* stream was open. Changes only when the list is read again (mount,
|
|
69
|
+
* `devicechange`, a grant), and not when an enumeration fails.
|
|
70
|
+
*/
|
|
71
|
+
hasLabels: boolean;
|
|
82
72
|
hasPermission: boolean;
|
|
83
73
|
isLoading: boolean;
|
|
84
74
|
requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>;
|
|
@@ -221,7 +211,21 @@ interface UseIntegratedRecordingReturn {
|
|
|
221
211
|
error: Error | null;
|
|
222
212
|
stream: MediaStream | null;
|
|
223
213
|
devices: MicrophoneDevice[];
|
|
214
|
+
/** `useMicrophoneAccess`'s `hasLabels`: `devices` names the real
|
|
215
|
+
* microphones, so a picker can offer them before one is open and open only
|
|
216
|
+
* the one chosen, with `changeDevice(id)`. */
|
|
217
|
+
hasLabels: boolean;
|
|
224
218
|
hasPermission: boolean;
|
|
219
|
+
/**
|
|
220
|
+
* The id of the microphone that is open: the device the stream's track
|
|
221
|
+
* reports (`getSettings().deviceId`), `null` while no stream is open (also
|
|
222
|
+
* while a request is opening one: it closes the open stream first). It is
|
|
223
|
+
* read from the stream, so it names the microphone that records; a picker
|
|
224
|
+
* shows it only when `devices` holds it. For a stream opened without an id
|
|
225
|
+
* (`requestMicAccess()`), Chromium reported `'default'`, the id of its list's
|
|
226
|
+
* default entry, and Firefox and WebKit the device's own id (headless runs
|
|
227
|
+
* with fake devices).
|
|
228
|
+
*/
|
|
225
229
|
selectedDevice: string | null;
|
|
226
230
|
/** Start capturing on the selected track. Resolves `true` when the capture
|
|
227
231
|
* pipeline actually started — callers that synchronize playback with
|
|
@@ -232,8 +236,13 @@ interface UseIntegratedRecordingReturn {
|
|
|
232
236
|
* (still loading, failed to load, or a clip that cannot be made from it). */
|
|
233
237
|
startRecording: () => Promise<boolean>;
|
|
234
238
|
/** Stop the take and add it to the track it was started on, with one
|
|
235
|
-
* `arrangement.updateTrack()`: one undo step.
|
|
236
|
-
|
|
239
|
+
* `arrangement.updateTrack()`: one undo step. Resolves when the take is on
|
|
240
|
+
* its track (or was refused, with `error` set); it never rejects.
|
|
241
|
+
*
|
|
242
|
+
* A take that ends without this call is added the same way: when the
|
|
243
|
+
* microphone is unplugged (`error` then says so), and when the component
|
|
244
|
+
* using the hook unmounts or is hidden mid-take. */
|
|
245
|
+
stopRecording: () => Promise<void>;
|
|
237
246
|
pauseRecording: () => void;
|
|
238
247
|
resumeRecording: () => void;
|
|
239
248
|
requestMicAccess: () => Promise<void>;
|
|
@@ -255,4 +264,4 @@ declare function useIntegratedRecording(arrangement: Arrangement, selectedTrackI
|
|
|
255
264
|
*/
|
|
256
265
|
declare function useRecordingProgress(progress: RecordingProgressSource, options?: UseThrottledValueOptions): RecordingProgress;
|
|
257
266
|
|
|
258
|
-
export { type IntegratedRecordingOptions, type MicrophoneDevice, type
|
|
267
|
+
export { type IntegratedRecordingOptions, type MicrophoneDevice, type RecordingOptions, type UseIntegratedRecordingReturn, type UseMicrophoneAccessReturn, type UseMicrophoneLevelOptions, type UseMicrophoneLevelReturn, type UseRecordingReturn, useIntegratedRecording, useMicrophoneAccess, useMicrophoneLevel, useRecording, useRecordingProgress };
|
package/dist/index.d.ts
CHANGED
|
@@ -6,17 +6,6 @@ import { UseThrottledValueOptions } from '@waveform-playlist/ui-components';
|
|
|
6
6
|
* Types for the recording package
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
interface RecordingState {
|
|
10
|
-
isRecording: boolean;
|
|
11
|
-
isPaused: boolean;
|
|
12
|
-
duration: number;
|
|
13
|
-
sampleRate: number;
|
|
14
|
-
}
|
|
15
|
-
interface RecordingData {
|
|
16
|
-
buffer: AudioBuffer | null;
|
|
17
|
-
peaks: (Int8Array | Int16Array)[];
|
|
18
|
-
duration: number;
|
|
19
|
-
}
|
|
20
9
|
interface MicrophoneDevice {
|
|
21
10
|
deviceId: string;
|
|
22
11
|
label: string;
|
|
@@ -41,16 +30,6 @@ interface RecordingOptions {
|
|
|
41
30
|
* Default: 16
|
|
42
31
|
*/
|
|
43
32
|
bits?: 8 | 16;
|
|
44
|
-
/**
|
|
45
|
-
* Specific device ID to use for recording
|
|
46
|
-
*/
|
|
47
|
-
deviceId?: string;
|
|
48
|
-
/**
|
|
49
|
-
* MediaTrackConstraints for audio recording
|
|
50
|
-
* Use this to customize echo cancellation, noise suppression, auto gain control, latency, etc.
|
|
51
|
-
* Default: Recording-optimized settings (all processing disabled, latency: 0 for low latency)
|
|
52
|
-
*/
|
|
53
|
-
audioConstraints?: MediaTrackConstraints;
|
|
54
33
|
}
|
|
55
34
|
interface UseRecordingReturn {
|
|
56
35
|
isRecording: boolean;
|
|
@@ -79,6 +58,17 @@ interface UseRecordingReturn {
|
|
|
79
58
|
interface UseMicrophoneAccessReturn {
|
|
80
59
|
stream: MediaStream | null;
|
|
81
60
|
devices: MicrophoneDevice[];
|
|
61
|
+
/**
|
|
62
|
+
* True when `devices` names the real microphones, with their ids and
|
|
63
|
+
* labels. Browsers hide them until microphone permission is granted (the
|
|
64
|
+
* list is then usually one entry with an empty `deviceId`). Chromium holding
|
|
65
|
+
* the permission listed them before any stream was open (headless runs with
|
|
66
|
+
* fake devices), so a picker can offer them and open only the one chosen,
|
|
67
|
+
* with `requestAccess(deviceId)`; Firefox and WebKit listed them only once a
|
|
68
|
+
* stream was open. Changes only when the list is read again (mount,
|
|
69
|
+
* `devicechange`, a grant), and not when an enumeration fails.
|
|
70
|
+
*/
|
|
71
|
+
hasLabels: boolean;
|
|
82
72
|
hasPermission: boolean;
|
|
83
73
|
isLoading: boolean;
|
|
84
74
|
requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>;
|
|
@@ -221,7 +211,21 @@ interface UseIntegratedRecordingReturn {
|
|
|
221
211
|
error: Error | null;
|
|
222
212
|
stream: MediaStream | null;
|
|
223
213
|
devices: MicrophoneDevice[];
|
|
214
|
+
/** `useMicrophoneAccess`'s `hasLabels`: `devices` names the real
|
|
215
|
+
* microphones, so a picker can offer them before one is open and open only
|
|
216
|
+
* the one chosen, with `changeDevice(id)`. */
|
|
217
|
+
hasLabels: boolean;
|
|
224
218
|
hasPermission: boolean;
|
|
219
|
+
/**
|
|
220
|
+
* The id of the microphone that is open: the device the stream's track
|
|
221
|
+
* reports (`getSettings().deviceId`), `null` while no stream is open (also
|
|
222
|
+
* while a request is opening one: it closes the open stream first). It is
|
|
223
|
+
* read from the stream, so it names the microphone that records; a picker
|
|
224
|
+
* shows it only when `devices` holds it. For a stream opened without an id
|
|
225
|
+
* (`requestMicAccess()`), Chromium reported `'default'`, the id of its list's
|
|
226
|
+
* default entry, and Firefox and WebKit the device's own id (headless runs
|
|
227
|
+
* with fake devices).
|
|
228
|
+
*/
|
|
225
229
|
selectedDevice: string | null;
|
|
226
230
|
/** Start capturing on the selected track. Resolves `true` when the capture
|
|
227
231
|
* pipeline actually started — callers that synchronize playback with
|
|
@@ -232,8 +236,13 @@ interface UseIntegratedRecordingReturn {
|
|
|
232
236
|
* (still loading, failed to load, or a clip that cannot be made from it). */
|
|
233
237
|
startRecording: () => Promise<boolean>;
|
|
234
238
|
/** Stop the take and add it to the track it was started on, with one
|
|
235
|
-
* `arrangement.updateTrack()`: one undo step.
|
|
236
|
-
|
|
239
|
+
* `arrangement.updateTrack()`: one undo step. Resolves when the take is on
|
|
240
|
+
* its track (or was refused, with `error` set); it never rejects.
|
|
241
|
+
*
|
|
242
|
+
* A take that ends without this call is added the same way: when the
|
|
243
|
+
* microphone is unplugged (`error` then says so), and when the component
|
|
244
|
+
* using the hook unmounts or is hidden mid-take. */
|
|
245
|
+
stopRecording: () => Promise<void>;
|
|
237
246
|
pauseRecording: () => void;
|
|
238
247
|
resumeRecording: () => void;
|
|
239
248
|
requestMicAccess: () => Promise<void>;
|
|
@@ -255,4 +264,4 @@ declare function useIntegratedRecording(arrangement: Arrangement, selectedTrackI
|
|
|
255
264
|
*/
|
|
256
265
|
declare function useRecordingProgress(progress: RecordingProgressSource, options?: UseThrottledValueOptions): RecordingProgress;
|
|
257
266
|
|
|
258
|
-
export { type IntegratedRecordingOptions, type MicrophoneDevice, type
|
|
267
|
+
export { type IntegratedRecordingOptions, type MicrophoneDevice, type RecordingOptions, type UseIntegratedRecordingReturn, type UseMicrophoneAccessReturn, type UseMicrophoneLevelOptions, type UseMicrophoneLevelReturn, type UseRecordingReturn, useIntegratedRecording, useMicrophoneAccess, useMicrophoneLevel, useRecording, useRecordingProgress };
|
package/dist/index.js
CHANGED
|
@@ -37,6 +37,9 @@ function emptyPeaks(bits) {
|
|
|
37
37
|
return bits === 8 ? new Int8Array(0) : new Int16Array(0);
|
|
38
38
|
}
|
|
39
39
|
function useRecording(stream, options = {}) {
|
|
40
|
+
return useRecordingWithTakeEnded(stream, options);
|
|
41
|
+
}
|
|
42
|
+
function useRecordingWithTakeEnded(stream, options = {}, onTakeEnded) {
|
|
40
43
|
const { channelCount = 1, samplesPerPixel = 1024, bits = 16 } = options;
|
|
41
44
|
const [isRecording, setIsRecording] = (0, import_react.useState)(false);
|
|
42
45
|
const [isPaused, setIsPaused] = (0, import_react.useState)(false);
|
|
@@ -63,7 +66,10 @@ function useRecording(stream, options = {}) {
|
|
|
63
66
|
const finishStopRecordingRef = (0, import_react.useRef)(null);
|
|
64
67
|
const isStartingRef = (0, import_react.useRef)(false);
|
|
65
68
|
const isUnmountedRef = (0, import_react.useRef)(false);
|
|
69
|
+
const mountEpochRef = (0, import_react.useRef)(0);
|
|
66
70
|
const durationRef = (0, import_react.useRef)(0);
|
|
71
|
+
const onTakeEndedRef = (0, import_react.useRef)(onTakeEnded);
|
|
72
|
+
onTakeEndedRef.current = onTakeEnded;
|
|
67
73
|
const peaksRef = (0, import_react.useRef)(progress.getSnapshot().peaks);
|
|
68
74
|
const publishProgress = (0, import_react.useCallback)(() => {
|
|
69
75
|
const current = progress.getSnapshot();
|
|
@@ -101,7 +107,16 @@ function useRecording(stream, options = {}) {
|
|
|
101
107
|
setError(new Error("No microphone stream available"));
|
|
102
108
|
return false;
|
|
103
109
|
}
|
|
110
|
+
if (stream.getAudioTracks()[0]?.readyState === "ended") {
|
|
111
|
+
setError(
|
|
112
|
+
new Error(
|
|
113
|
+
"The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again."
|
|
114
|
+
)
|
|
115
|
+
);
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
104
118
|
isStartingRef.current = true;
|
|
119
|
+
const mountEpoch = mountEpochRef.current;
|
|
105
120
|
try {
|
|
106
121
|
setError(null);
|
|
107
122
|
const context = (0, import_playout.getGlobalContext)();
|
|
@@ -109,7 +124,7 @@ function useRecording(stream, options = {}) {
|
|
|
109
124
|
await context.resume();
|
|
110
125
|
}
|
|
111
126
|
await loadWorklet();
|
|
112
|
-
if (isUnmountedRef.current) return false;
|
|
127
|
+
if (isUnmountedRef.current || mountEpoch !== mountEpochRef.current) return false;
|
|
113
128
|
const source = context.createMediaStreamSource(stream);
|
|
114
129
|
mediaStreamSourceRef.current = source;
|
|
115
130
|
const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings().channelCount;
|
|
@@ -174,8 +189,9 @@ function useRecording(stream, options = {}) {
|
|
|
174
189
|
if (audioTrack) {
|
|
175
190
|
const onEnded = () => {
|
|
176
191
|
console.warn("[waveform-playlist] Audio track ended (mic unplugged or revoked)");
|
|
177
|
-
stopRecordingRef.current?.();
|
|
192
|
+
const stopped = stopRecordingRef.current?.();
|
|
178
193
|
setError(new Error("Microphone disconnected during recording"));
|
|
194
|
+
stopped?.then((buffer) => onTakeEndedRef.current?.(buffer));
|
|
179
195
|
};
|
|
180
196
|
onTrackEndedRef.current = onEnded;
|
|
181
197
|
audioTrack.addEventListener("ended", onEnded);
|
|
@@ -215,6 +231,18 @@ function useRecording(stream, options = {}) {
|
|
|
215
231
|
stopPromiseRef.current = stopPromise;
|
|
216
232
|
return stopPromise;
|
|
217
233
|
}, []);
|
|
234
|
+
const buildTakeBuffer = (0, import_react.useCallback)(() => {
|
|
235
|
+
const context = (0, import_playout.getGlobalContext)();
|
|
236
|
+
const rawContext = context.rawContext;
|
|
237
|
+
const numChannels = recordedChunksRef.current.length || channelCount;
|
|
238
|
+
const channelData = recordedChunksRef.current.map((chunks) => (0, import_core.concatenateAudioData)(chunks));
|
|
239
|
+
const totalSamples = channelData[0]?.length ?? 0;
|
|
240
|
+
if (totalSamples === 0) {
|
|
241
|
+
console.warn("[waveform-playlist] Recording stopped with 0 samples captured \u2014 discarding");
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
return (0, import_core.createAudioBuffer)(rawContext, channelData, rawContext.sampleRate, numChannels);
|
|
245
|
+
}, [channelCount]);
|
|
218
246
|
const finishStopRecording = (0, import_react.useCallback)(async () => {
|
|
219
247
|
try {
|
|
220
248
|
if (animationFrameRef.current !== null) {
|
|
@@ -262,16 +290,8 @@ function useRecording(stream, options = {}) {
|
|
|
262
290
|
workletNodeRef.current = null;
|
|
263
291
|
mediaStreamSourceRef.current = null;
|
|
264
292
|
}
|
|
265
|
-
const
|
|
266
|
-
|
|
267
|
-
const numChannels = recordedChunksRef.current.length || channelCount;
|
|
268
|
-
const channelData = recordedChunksRef.current.map((chunks) => (0, import_core.concatenateAudioData)(chunks));
|
|
269
|
-
const totalSamples = channelData[0]?.length ?? 0;
|
|
270
|
-
if (totalSamples === 0) {
|
|
271
|
-
console.warn("[waveform-playlist] Recording stopped with 0 samples captured \u2014 discarding");
|
|
272
|
-
return null;
|
|
273
|
-
}
|
|
274
|
-
const buffer = (0, import_core.createAudioBuffer)(rawContext, channelData, rawContext.sampleRate, numChannels);
|
|
293
|
+
const buffer = buildTakeBuffer();
|
|
294
|
+
if (!buffer) return null;
|
|
275
295
|
setAudioBuffer(buffer);
|
|
276
296
|
durationRef.current = buffer.duration;
|
|
277
297
|
publishProgress();
|
|
@@ -287,9 +307,11 @@ function useRecording(stream, options = {}) {
|
|
|
287
307
|
setIsRecording(false);
|
|
288
308
|
setIsPaused(false);
|
|
289
309
|
}
|
|
290
|
-
}, [
|
|
310
|
+
}, [buildTakeBuffer, publishProgress]);
|
|
291
311
|
stopRecordingRef.current = stopRecording;
|
|
292
312
|
finishStopRecordingRef.current = finishStopRecording;
|
|
313
|
+
const buildTakeBufferRef = (0, import_react.useRef)(buildTakeBuffer);
|
|
314
|
+
buildTakeBufferRef.current = buildTakeBuffer;
|
|
293
315
|
const pauseRecording = (0, import_react.useCallback)(() => {
|
|
294
316
|
if (isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current) {
|
|
295
317
|
workletNodeRef.current?.port.postMessage({ command: "pause" });
|
|
@@ -313,6 +335,7 @@ function useRecording(stream, options = {}) {
|
|
|
313
335
|
}, [startDurationLoop]);
|
|
314
336
|
(0, import_react.useEffect)(() => {
|
|
315
337
|
isUnmountedRef.current = false;
|
|
338
|
+
mountEpochRef.current += 1;
|
|
316
339
|
return () => {
|
|
317
340
|
isUnmountedRef.current = true;
|
|
318
341
|
if (audioTrackRef.current && onTrackEndedRef.current) {
|
|
@@ -336,6 +359,28 @@ function useRecording(stream, options = {}) {
|
|
|
336
359
|
}
|
|
337
360
|
if (animationFrameRef.current !== null) {
|
|
338
361
|
cancelAnimationFrame(animationFrameRef.current);
|
|
362
|
+
animationFrameRef.current = null;
|
|
363
|
+
}
|
|
364
|
+
if (!isRecordingRef.current || isStoppingRef.current) return;
|
|
365
|
+
isRecordingRef.current = false;
|
|
366
|
+
isPausedRef.current = false;
|
|
367
|
+
workletNodeRef.current = null;
|
|
368
|
+
mediaStreamSourceRef.current = null;
|
|
369
|
+
audioTrackRef.current = null;
|
|
370
|
+
onTrackEndedRef.current = null;
|
|
371
|
+
let buffer = null;
|
|
372
|
+
try {
|
|
373
|
+
buffer = buildTakeBufferRef.current();
|
|
374
|
+
} catch (err) {
|
|
375
|
+
console.warn("[waveform-playlist] Failed to keep the interrupted take:", String(err));
|
|
376
|
+
}
|
|
377
|
+
setIsRecording(false);
|
|
378
|
+
setIsPaused(false);
|
|
379
|
+
if (buffer) setAudioBuffer(buffer);
|
|
380
|
+
try {
|
|
381
|
+
onTakeEndedRef.current?.(buffer);
|
|
382
|
+
} catch (err) {
|
|
383
|
+
console.warn("[waveform-playlist] Failed to hand over the interrupted take:", String(err));
|
|
339
384
|
}
|
|
340
385
|
};
|
|
341
386
|
}, []);
|
|
@@ -358,6 +403,7 @@ var import_core2 = require("@waveform-playlist/core");
|
|
|
358
403
|
function useMicrophoneAccess() {
|
|
359
404
|
const [stream, setStream] = (0, import_react2.useState)(null);
|
|
360
405
|
const [devices, setDevices] = (0, import_react2.useState)([]);
|
|
406
|
+
const [hasLabels, setHasLabels] = (0, import_react2.useState)(false);
|
|
361
407
|
const [hasPermission, setHasPermission] = (0, import_react2.useState)(false);
|
|
362
408
|
const [isLoading, setIsLoading] = (0, import_react2.useState)(false);
|
|
363
409
|
const [error, setError] = (0, import_react2.useState)(null);
|
|
@@ -366,10 +412,11 @@ function useMicrophoneAccess() {
|
|
|
366
412
|
const isUnmountedRef = (0, import_react2.useRef)(false);
|
|
367
413
|
const enumerateDevices = (0, import_react2.useCallback)(async () => {
|
|
368
414
|
try {
|
|
369
|
-
const { devices: audioInputs } = await (0, import_core2.enumerateMicrophones)();
|
|
415
|
+
const { devices: audioInputs, hasLabels: labelled } = await (0, import_core2.enumerateMicrophones)();
|
|
370
416
|
setDevices(audioInputs);
|
|
417
|
+
setHasLabels(labelled);
|
|
371
418
|
} catch (err) {
|
|
372
|
-
console.
|
|
419
|
+
console.warn("[waveform-playlist] Failed to enumerate devices:", String(err));
|
|
373
420
|
setError(err instanceof Error ? err : new Error("Failed to enumerate devices"));
|
|
374
421
|
}
|
|
375
422
|
}, []);
|
|
@@ -400,7 +447,13 @@ function useMicrophoneAccess() {
|
|
|
400
447
|
audio,
|
|
401
448
|
video: false
|
|
402
449
|
};
|
|
403
|
-
const
|
|
450
|
+
const mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : void 0;
|
|
451
|
+
if (!mediaDevices || typeof mediaDevices.getUserMedia !== "function") {
|
|
452
|
+
throw new Error(
|
|
453
|
+
"Microphone access is not available: navigator.mediaDevices is undefined. It needs a secure context (https or localhost)."
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
const newStream = await mediaDevices.getUserMedia(constraints);
|
|
404
457
|
if (generation !== requestGenerationRef.current || isUnmountedRef.current) {
|
|
405
458
|
newStream.getTracks().forEach((track) => track.stop());
|
|
406
459
|
return;
|
|
@@ -408,9 +461,21 @@ function useMicrophoneAccess() {
|
|
|
408
461
|
streamRef.current = newStream;
|
|
409
462
|
setStream(newStream);
|
|
410
463
|
setHasPermission(true);
|
|
464
|
+
const onEnded = () => {
|
|
465
|
+
if (streamRef.current !== newStream) return;
|
|
466
|
+
streamRef.current = null;
|
|
467
|
+
setStream(null);
|
|
468
|
+
setHasPermission(false);
|
|
469
|
+
setError(
|
|
470
|
+
new Error(
|
|
471
|
+
"The microphone was disconnected or its permission was revoked. Request microphone access again."
|
|
472
|
+
)
|
|
473
|
+
);
|
|
474
|
+
};
|
|
475
|
+
newStream.getTracks().forEach((track) => track.addEventListener("ended", onEnded, { once: true }));
|
|
411
476
|
await enumerateDevices();
|
|
412
477
|
} catch (err) {
|
|
413
|
-
console.
|
|
478
|
+
console.warn("[waveform-playlist] Failed to access microphone:", String(err));
|
|
414
479
|
if (generation === requestGenerationRef.current) {
|
|
415
480
|
setError(err instanceof Error ? err : new Error("Failed to access microphone"));
|
|
416
481
|
setHasPermission(false);
|
|
@@ -435,19 +500,23 @@ function useMicrophoneAccess() {
|
|
|
435
500
|
(0, import_react2.useEffect)(() => {
|
|
436
501
|
isUnmountedRef.current = false;
|
|
437
502
|
enumerateDevices();
|
|
438
|
-
navigator
|
|
503
|
+
const mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : void 0;
|
|
504
|
+
mediaDevices?.addEventListener("devicechange", enumerateDevices);
|
|
439
505
|
return () => {
|
|
440
|
-
|
|
506
|
+
mediaDevices?.removeEventListener("devicechange", enumerateDevices);
|
|
441
507
|
isUnmountedRef.current = true;
|
|
442
508
|
if (streamRef.current) {
|
|
443
509
|
streamRef.current.getTracks().forEach((track) => track.stop());
|
|
444
510
|
streamRef.current = null;
|
|
511
|
+
setStream(null);
|
|
512
|
+
setHasPermission(false);
|
|
445
513
|
}
|
|
446
514
|
};
|
|
447
515
|
}, [enumerateDevices]);
|
|
448
516
|
return {
|
|
449
517
|
stream,
|
|
450
518
|
devices,
|
|
519
|
+
hasLabels,
|
|
451
520
|
hasPermission,
|
|
452
521
|
isLoading,
|
|
453
522
|
requestAccess,
|
|
@@ -630,8 +699,7 @@ var import_core5 = require("@waveform-playlist/core");
|
|
|
630
699
|
var import_playout3 = require("@waveform-playlist/playout");
|
|
631
700
|
function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
632
701
|
const { currentTime = 0, audioConstraints, latencyOffset, ...recordingOptions } = options;
|
|
633
|
-
const
|
|
634
|
-
const [selectedDevice, setSelectedDevice] = (0, import_react4.useState)(null);
|
|
702
|
+
const audioResumedRef = (0, import_react4.useRef)(false);
|
|
635
703
|
const [hookError, setHookError] = (0, import_react4.useState)(null);
|
|
636
704
|
const recordingStartTimeRef = (0, import_react4.useRef)(0);
|
|
637
705
|
const recordingTrackIdRef = (0, import_react4.useRef)(null);
|
|
@@ -641,7 +709,19 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
641
709
|
selectedTrackIdRef.current = selectedTrackId;
|
|
642
710
|
const currentTimeRef = (0, import_react4.useRef)(currentTime);
|
|
643
711
|
currentTimeRef.current = currentTime;
|
|
644
|
-
const
|
|
712
|
+
const audioConstraintsRef = (0, import_react4.useRef)(audioConstraints);
|
|
713
|
+
audioConstraintsRef.current = audioConstraints;
|
|
714
|
+
const finishTakeRef = (0, import_react4.useRef)(() => {
|
|
715
|
+
});
|
|
716
|
+
const {
|
|
717
|
+
stream,
|
|
718
|
+
devices,
|
|
719
|
+
hasLabels,
|
|
720
|
+
hasPermission,
|
|
721
|
+
requestAccess,
|
|
722
|
+
error: micError
|
|
723
|
+
} = useMicrophoneAccess();
|
|
724
|
+
const selectedDevice = (0, import_react4.useMemo)(() => openDeviceId(stream), [stream]);
|
|
645
725
|
const {
|
|
646
726
|
meter,
|
|
647
727
|
resetPeak,
|
|
@@ -658,7 +738,16 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
658
738
|
pauseRecording,
|
|
659
739
|
resumeRecording,
|
|
660
740
|
error: recError
|
|
661
|
-
} =
|
|
741
|
+
} = useRecordingWithTakeEnded(
|
|
742
|
+
stream,
|
|
743
|
+
recordingOptions,
|
|
744
|
+
(buffer) => (
|
|
745
|
+
// The take ended without our stopRecording(): keep it (#822).
|
|
746
|
+
finishTakeRef.current(buffer)
|
|
747
|
+
)
|
|
748
|
+
);
|
|
749
|
+
const startRecRef = (0, import_react4.useRef)(startRec);
|
|
750
|
+
startRecRef.current = startRec;
|
|
662
751
|
const startRecording = (0, import_react4.useCallback)(async () => {
|
|
663
752
|
if (isRecordingRef.current || isStartingRef.current) return false;
|
|
664
753
|
if (!selectedTrackIdRef.current) {
|
|
@@ -675,14 +764,14 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
675
764
|
isStartingRef.current = true;
|
|
676
765
|
try {
|
|
677
766
|
setHookError(null);
|
|
678
|
-
if (!
|
|
767
|
+
if (!audioResumedRef.current) {
|
|
679
768
|
await (0, import_playout3.resumeGlobalAudioContext)();
|
|
680
|
-
|
|
769
|
+
audioResumedRef.current = true;
|
|
681
770
|
}
|
|
682
771
|
recordingStartTimeRef.current = currentTimeRef.current;
|
|
683
772
|
recordingTrackIdRef.current = selectedTrackIdRef.current;
|
|
684
773
|
setRecordingTrackId(selectedTrackIdRef.current);
|
|
685
|
-
const started = await
|
|
774
|
+
const started = await startRecRef.current();
|
|
686
775
|
if (!started) setRecordingTrackId(null);
|
|
687
776
|
return started;
|
|
688
777
|
} catch (err) {
|
|
@@ -692,19 +781,14 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
692
781
|
} finally {
|
|
693
782
|
isStartingRef.current = false;
|
|
694
783
|
}
|
|
695
|
-
}, [arrangement
|
|
696
|
-
const
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
setHookError(err instanceof Error ? err : new Error(String(err)));
|
|
702
|
-
return;
|
|
703
|
-
} finally {
|
|
784
|
+
}, [arrangement]);
|
|
785
|
+
const finishTake = (0, import_react4.useCallback)(
|
|
786
|
+
(buffer) => {
|
|
787
|
+
if (!buffer) return;
|
|
788
|
+
const trackId = recordingTrackIdRef.current;
|
|
789
|
+
recordingTrackIdRef.current = null;
|
|
704
790
|
setRecordingTrackId(null);
|
|
705
|
-
|
|
706
|
-
const trackId = recordingTrackIdRef.current;
|
|
707
|
-
if (buffer && trackId) {
|
|
791
|
+
if (!trackId) return;
|
|
708
792
|
if (!arrangement.getTracks().some((t) => t.id === trackId)) {
|
|
709
793
|
const err = new Error(
|
|
710
794
|
`Recording completed but track "${trackId}" no longer exists. The recorded audio could not be saved.`
|
|
@@ -750,19 +834,19 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
750
834
|
console.warn(`[waveform-playlist] ${notSaved.message}`);
|
|
751
835
|
setHookError(notSaved);
|
|
752
836
|
}
|
|
837
|
+
},
|
|
838
|
+
[arrangement, latencyOffset]
|
|
839
|
+
);
|
|
840
|
+
finishTakeRef.current = finishTake;
|
|
841
|
+
const stopRecording = (0, import_react4.useCallback)(async () => {
|
|
842
|
+
let buffer = null;
|
|
843
|
+
try {
|
|
844
|
+
buffer = await stopRec();
|
|
845
|
+
} catch (err) {
|
|
846
|
+
setHookError(err instanceof Error ? err : new Error(String(err)));
|
|
753
847
|
}
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
if (!hasPermission || devices.length === 0) return;
|
|
757
|
-
if (selectedDevice === null) {
|
|
758
|
-
setSelectedDevice(devices[0].deviceId);
|
|
759
|
-
} else if (!devices.some((d) => d.deviceId === selectedDevice)) {
|
|
760
|
-
const fallbackId = devices[0].deviceId;
|
|
761
|
-
setSelectedDevice(fallbackId);
|
|
762
|
-
resetPeak();
|
|
763
|
-
requestAccess(fallbackId, audioConstraints);
|
|
764
|
-
}
|
|
765
|
-
}, [hasPermission, devices, selectedDevice, resetPeak, requestAccess, audioConstraints]);
|
|
848
|
+
finishTakeRef.current(buffer);
|
|
849
|
+
}, [stopRec]);
|
|
766
850
|
const isRecordingRef = (0, import_react4.useRef)(isRecording);
|
|
767
851
|
isRecordingRef.current = isRecording;
|
|
768
852
|
const requestMicAccess = (0, import_react4.useCallback)(async () => {
|
|
@@ -772,13 +856,13 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
772
856
|
}
|
|
773
857
|
try {
|
|
774
858
|
setHookError(null);
|
|
775
|
-
await requestAccess(void 0,
|
|
859
|
+
await requestAccess(void 0, audioConstraintsRef.current);
|
|
776
860
|
await (0, import_playout3.resumeGlobalAudioContext)();
|
|
777
|
-
|
|
861
|
+
audioResumedRef.current = true;
|
|
778
862
|
} catch (err) {
|
|
779
863
|
setHookError(err instanceof Error ? err : new Error(String(err)));
|
|
780
864
|
}
|
|
781
|
-
}, [requestAccess
|
|
865
|
+
}, [requestAccess]);
|
|
782
866
|
const changeDevice = (0, import_react4.useCallback)(
|
|
783
867
|
async (deviceId) => {
|
|
784
868
|
if (isRecordingRef.current) {
|
|
@@ -787,16 +871,15 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
787
871
|
}
|
|
788
872
|
try {
|
|
789
873
|
setHookError(null);
|
|
790
|
-
setSelectedDevice(deviceId);
|
|
791
874
|
resetPeak();
|
|
792
|
-
await requestAccess(deviceId,
|
|
875
|
+
await requestAccess(deviceId, audioConstraintsRef.current);
|
|
793
876
|
await (0, import_playout3.resumeGlobalAudioContext)();
|
|
794
|
-
|
|
877
|
+
audioResumedRef.current = true;
|
|
795
878
|
} catch (err) {
|
|
796
879
|
setHookError(err instanceof Error ? err : new Error(String(err)));
|
|
797
880
|
}
|
|
798
881
|
},
|
|
799
|
-
[requestAccess,
|
|
882
|
+
[requestAccess, resetPeak]
|
|
800
883
|
);
|
|
801
884
|
return {
|
|
802
885
|
// Recording state
|
|
@@ -811,6 +894,7 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
811
894
|
// Microphone state
|
|
812
895
|
stream,
|
|
813
896
|
devices,
|
|
897
|
+
hasLabels,
|
|
814
898
|
hasPermission,
|
|
815
899
|
selectedDevice,
|
|
816
900
|
// Recording controls
|
|
@@ -822,6 +906,10 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
|
|
|
822
906
|
changeDevice
|
|
823
907
|
};
|
|
824
908
|
}
|
|
909
|
+
function openDeviceId(stream) {
|
|
910
|
+
const track = stream?.getAudioTracks()[0];
|
|
911
|
+
return track?.getSettings?.().deviceId || null;
|
|
912
|
+
}
|
|
825
913
|
|
|
826
914
|
// src/hooks/useRecordingProgress.ts
|
|
827
915
|
var import_ui_components = require("@waveform-playlist/ui-components");
|