@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/dist/index.mjs CHANGED
@@ -12,6 +12,9 @@ function emptyPeaks(bits) {
12
12
  return bits === 8 ? new Int8Array(0) : new Int16Array(0);
13
13
  }
14
14
  function useRecording(stream, options = {}) {
15
+ return useRecordingWithTakeEnded(stream, options);
16
+ }
17
+ function useRecordingWithTakeEnded(stream, options = {}, onTakeEnded) {
15
18
  const { channelCount = 1, samplesPerPixel = 1024, bits = 16 } = options;
16
19
  const [isRecording, setIsRecording] = useState(false);
17
20
  const [isPaused, setIsPaused] = useState(false);
@@ -38,7 +41,10 @@ function useRecording(stream, options = {}) {
38
41
  const finishStopRecordingRef = useRef(null);
39
42
  const isStartingRef = useRef(false);
40
43
  const isUnmountedRef = useRef(false);
44
+ const mountEpochRef = useRef(0);
41
45
  const durationRef = useRef(0);
46
+ const onTakeEndedRef = useRef(onTakeEnded);
47
+ onTakeEndedRef.current = onTakeEnded;
42
48
  const peaksRef = useRef(progress.getSnapshot().peaks);
43
49
  const publishProgress = useCallback(() => {
44
50
  const current = progress.getSnapshot();
@@ -76,7 +82,16 @@ function useRecording(stream, options = {}) {
76
82
  setError(new Error("No microphone stream available"));
77
83
  return false;
78
84
  }
85
+ if (stream.getAudioTracks()[0]?.readyState === "ended") {
86
+ setError(
87
+ new Error(
88
+ "The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again."
89
+ )
90
+ );
91
+ return false;
92
+ }
79
93
  isStartingRef.current = true;
94
+ const mountEpoch = mountEpochRef.current;
80
95
  try {
81
96
  setError(null);
82
97
  const context = getGlobalContext();
@@ -84,7 +99,7 @@ function useRecording(stream, options = {}) {
84
99
  await context.resume();
85
100
  }
86
101
  await loadWorklet();
87
- if (isUnmountedRef.current) return false;
102
+ if (isUnmountedRef.current || mountEpoch !== mountEpochRef.current) return false;
88
103
  const source = context.createMediaStreamSource(stream);
89
104
  mediaStreamSourceRef.current = source;
90
105
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings().channelCount;
@@ -149,8 +164,9 @@ function useRecording(stream, options = {}) {
149
164
  if (audioTrack) {
150
165
  const onEnded = () => {
151
166
  console.warn("[waveform-playlist] Audio track ended (mic unplugged or revoked)");
152
- stopRecordingRef.current?.();
167
+ const stopped = stopRecordingRef.current?.();
153
168
  setError(new Error("Microphone disconnected during recording"));
169
+ stopped?.then((buffer) => onTakeEndedRef.current?.(buffer));
154
170
  };
155
171
  onTrackEndedRef.current = onEnded;
156
172
  audioTrack.addEventListener("ended", onEnded);
@@ -190,6 +206,18 @@ function useRecording(stream, options = {}) {
190
206
  stopPromiseRef.current = stopPromise;
191
207
  return stopPromise;
192
208
  }, []);
209
+ const buildTakeBuffer = useCallback(() => {
210
+ const context = getGlobalContext();
211
+ const rawContext = context.rawContext;
212
+ const numChannels = recordedChunksRef.current.length || channelCount;
213
+ const channelData = recordedChunksRef.current.map((chunks) => concatenateAudioData(chunks));
214
+ const totalSamples = channelData[0]?.length ?? 0;
215
+ if (totalSamples === 0) {
216
+ console.warn("[waveform-playlist] Recording stopped with 0 samples captured \u2014 discarding");
217
+ return null;
218
+ }
219
+ return createAudioBuffer(rawContext, channelData, rawContext.sampleRate, numChannels);
220
+ }, [channelCount]);
193
221
  const finishStopRecording = useCallback(async () => {
194
222
  try {
195
223
  if (animationFrameRef.current !== null) {
@@ -237,16 +265,8 @@ function useRecording(stream, options = {}) {
237
265
  workletNodeRef.current = null;
238
266
  mediaStreamSourceRef.current = null;
239
267
  }
240
- const context = getGlobalContext();
241
- const rawContext = context.rawContext;
242
- const numChannels = recordedChunksRef.current.length || channelCount;
243
- const channelData = recordedChunksRef.current.map((chunks) => concatenateAudioData(chunks));
244
- const totalSamples = channelData[0]?.length ?? 0;
245
- if (totalSamples === 0) {
246
- console.warn("[waveform-playlist] Recording stopped with 0 samples captured \u2014 discarding");
247
- return null;
248
- }
249
- const buffer = createAudioBuffer(rawContext, channelData, rawContext.sampleRate, numChannels);
268
+ const buffer = buildTakeBuffer();
269
+ if (!buffer) return null;
250
270
  setAudioBuffer(buffer);
251
271
  durationRef.current = buffer.duration;
252
272
  publishProgress();
@@ -262,9 +282,11 @@ function useRecording(stream, options = {}) {
262
282
  setIsRecording(false);
263
283
  setIsPaused(false);
264
284
  }
265
- }, [channelCount, publishProgress]);
285
+ }, [buildTakeBuffer, publishProgress]);
266
286
  stopRecordingRef.current = stopRecording;
267
287
  finishStopRecordingRef.current = finishStopRecording;
288
+ const buildTakeBufferRef = useRef(buildTakeBuffer);
289
+ buildTakeBufferRef.current = buildTakeBuffer;
268
290
  const pauseRecording = useCallback(() => {
269
291
  if (isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current) {
270
292
  workletNodeRef.current?.port.postMessage({ command: "pause" });
@@ -288,6 +310,7 @@ function useRecording(stream, options = {}) {
288
310
  }, [startDurationLoop]);
289
311
  useEffect(() => {
290
312
  isUnmountedRef.current = false;
313
+ mountEpochRef.current += 1;
291
314
  return () => {
292
315
  isUnmountedRef.current = true;
293
316
  if (audioTrackRef.current && onTrackEndedRef.current) {
@@ -311,6 +334,28 @@ function useRecording(stream, options = {}) {
311
334
  }
312
335
  if (animationFrameRef.current !== null) {
313
336
  cancelAnimationFrame(animationFrameRef.current);
337
+ animationFrameRef.current = null;
338
+ }
339
+ if (!isRecordingRef.current || isStoppingRef.current) return;
340
+ isRecordingRef.current = false;
341
+ isPausedRef.current = false;
342
+ workletNodeRef.current = null;
343
+ mediaStreamSourceRef.current = null;
344
+ audioTrackRef.current = null;
345
+ onTrackEndedRef.current = null;
346
+ let buffer = null;
347
+ try {
348
+ buffer = buildTakeBufferRef.current();
349
+ } catch (err) {
350
+ console.warn("[waveform-playlist] Failed to keep the interrupted take:", String(err));
351
+ }
352
+ setIsRecording(false);
353
+ setIsPaused(false);
354
+ if (buffer) setAudioBuffer(buffer);
355
+ try {
356
+ onTakeEndedRef.current?.(buffer);
357
+ } catch (err) {
358
+ console.warn("[waveform-playlist] Failed to hand over the interrupted take:", String(err));
314
359
  }
315
360
  };
316
361
  }, []);
@@ -333,6 +378,7 @@ import { enumerateMicrophones } from "@waveform-playlist/core";
333
378
  function useMicrophoneAccess() {
334
379
  const [stream, setStream] = useState2(null);
335
380
  const [devices, setDevices] = useState2([]);
381
+ const [hasLabels, setHasLabels] = useState2(false);
336
382
  const [hasPermission, setHasPermission] = useState2(false);
337
383
  const [isLoading, setIsLoading] = useState2(false);
338
384
  const [error, setError] = useState2(null);
@@ -341,10 +387,11 @@ function useMicrophoneAccess() {
341
387
  const isUnmountedRef = useRef2(false);
342
388
  const enumerateDevices = useCallback2(async () => {
343
389
  try {
344
- const { devices: audioInputs } = await enumerateMicrophones();
390
+ const { devices: audioInputs, hasLabels: labelled } = await enumerateMicrophones();
345
391
  setDevices(audioInputs);
392
+ setHasLabels(labelled);
346
393
  } catch (err) {
347
- console.error("Failed to enumerate devices:", err);
394
+ console.warn("[waveform-playlist] Failed to enumerate devices:", String(err));
348
395
  setError(err instanceof Error ? err : new Error("Failed to enumerate devices"));
349
396
  }
350
397
  }, []);
@@ -375,7 +422,13 @@ function useMicrophoneAccess() {
375
422
  audio,
376
423
  video: false
377
424
  };
378
- const newStream = await navigator.mediaDevices.getUserMedia(constraints);
425
+ const mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : void 0;
426
+ if (!mediaDevices || typeof mediaDevices.getUserMedia !== "function") {
427
+ throw new Error(
428
+ "Microphone access is not available: navigator.mediaDevices is undefined. It needs a secure context (https or localhost)."
429
+ );
430
+ }
431
+ const newStream = await mediaDevices.getUserMedia(constraints);
379
432
  if (generation !== requestGenerationRef.current || isUnmountedRef.current) {
380
433
  newStream.getTracks().forEach((track) => track.stop());
381
434
  return;
@@ -383,9 +436,21 @@ function useMicrophoneAccess() {
383
436
  streamRef.current = newStream;
384
437
  setStream(newStream);
385
438
  setHasPermission(true);
439
+ const onEnded = () => {
440
+ if (streamRef.current !== newStream) return;
441
+ streamRef.current = null;
442
+ setStream(null);
443
+ setHasPermission(false);
444
+ setError(
445
+ new Error(
446
+ "The microphone was disconnected or its permission was revoked. Request microphone access again."
447
+ )
448
+ );
449
+ };
450
+ newStream.getTracks().forEach((track) => track.addEventListener("ended", onEnded, { once: true }));
386
451
  await enumerateDevices();
387
452
  } catch (err) {
388
- console.error("Failed to access microphone:", err);
453
+ console.warn("[waveform-playlist] Failed to access microphone:", String(err));
389
454
  if (generation === requestGenerationRef.current) {
390
455
  setError(err instanceof Error ? err : new Error("Failed to access microphone"));
391
456
  setHasPermission(false);
@@ -410,19 +475,23 @@ function useMicrophoneAccess() {
410
475
  useEffect2(() => {
411
476
  isUnmountedRef.current = false;
412
477
  enumerateDevices();
413
- navigator.mediaDevices.addEventListener("devicechange", enumerateDevices);
478
+ const mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : void 0;
479
+ mediaDevices?.addEventListener("devicechange", enumerateDevices);
414
480
  return () => {
415
- navigator.mediaDevices.removeEventListener("devicechange", enumerateDevices);
481
+ mediaDevices?.removeEventListener("devicechange", enumerateDevices);
416
482
  isUnmountedRef.current = true;
417
483
  if (streamRef.current) {
418
484
  streamRef.current.getTracks().forEach((track) => track.stop());
419
485
  streamRef.current = null;
486
+ setStream(null);
487
+ setHasPermission(false);
420
488
  }
421
489
  };
422
490
  }, [enumerateDevices]);
423
491
  return {
424
492
  stream,
425
493
  devices,
494
+ hasLabels,
426
495
  hasPermission,
427
496
  isLoading,
428
497
  requestAccess,
@@ -537,7 +606,7 @@ function useMicrophoneLevel(stream, options = {}) {
537
606
  }
538
607
 
539
608
  // src/hooks/useIntegratedRecording.ts
540
- import { useState as useState4, useCallback as useCallback4, useEffect as useEffect4, useRef as useRef4 } from "react";
609
+ import { useState as useState4, useCallback as useCallback4, useMemo, useRef as useRef4 } from "react";
541
610
 
542
611
  // src/hooks/takeTarget.ts
543
612
  import {
@@ -619,8 +688,7 @@ import {
619
688
  } from "@waveform-playlist/playout";
620
689
  function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
621
690
  const { currentTime = 0, audioConstraints, latencyOffset, ...recordingOptions } = options;
622
- const [isMonitoring, setIsMonitoring] = useState4(false);
623
- const [selectedDevice, setSelectedDevice] = useState4(null);
691
+ const audioResumedRef = useRef4(false);
624
692
  const [hookError, setHookError] = useState4(null);
625
693
  const recordingStartTimeRef = useRef4(0);
626
694
  const recordingTrackIdRef = useRef4(null);
@@ -630,7 +698,19 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
630
698
  selectedTrackIdRef.current = selectedTrackId;
631
699
  const currentTimeRef = useRef4(currentTime);
632
700
  currentTimeRef.current = currentTime;
633
- const { stream, devices, hasPermission, requestAccess, error: micError } = useMicrophoneAccess();
701
+ const audioConstraintsRef = useRef4(audioConstraints);
702
+ audioConstraintsRef.current = audioConstraints;
703
+ const finishTakeRef = useRef4(() => {
704
+ });
705
+ const {
706
+ stream,
707
+ devices,
708
+ hasLabels,
709
+ hasPermission,
710
+ requestAccess,
711
+ error: micError
712
+ } = useMicrophoneAccess();
713
+ const selectedDevice = useMemo(() => openDeviceId(stream), [stream]);
634
714
  const {
635
715
  meter,
636
716
  resetPeak,
@@ -647,7 +727,16 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
647
727
  pauseRecording,
648
728
  resumeRecording,
649
729
  error: recError
650
- } = useRecording(stream, recordingOptions);
730
+ } = useRecordingWithTakeEnded(
731
+ stream,
732
+ recordingOptions,
733
+ (buffer) => (
734
+ // The take ended without our stopRecording(): keep it (#822).
735
+ finishTakeRef.current(buffer)
736
+ )
737
+ );
738
+ const startRecRef = useRef4(startRec);
739
+ startRecRef.current = startRec;
651
740
  const startRecording = useCallback4(async () => {
652
741
  if (isRecordingRef.current || isStartingRef.current) return false;
653
742
  if (!selectedTrackIdRef.current) {
@@ -664,14 +753,14 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
664
753
  isStartingRef.current = true;
665
754
  try {
666
755
  setHookError(null);
667
- if (!isMonitoring) {
756
+ if (!audioResumedRef.current) {
668
757
  await resumeGlobalAudioContext();
669
- setIsMonitoring(true);
758
+ audioResumedRef.current = true;
670
759
  }
671
760
  recordingStartTimeRef.current = currentTimeRef.current;
672
761
  recordingTrackIdRef.current = selectedTrackIdRef.current;
673
762
  setRecordingTrackId(selectedTrackIdRef.current);
674
- const started = await startRec();
763
+ const started = await startRecRef.current();
675
764
  if (!started) setRecordingTrackId(null);
676
765
  return started;
677
766
  } catch (err) {
@@ -681,19 +770,14 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
681
770
  } finally {
682
771
  isStartingRef.current = false;
683
772
  }
684
- }, [arrangement, isMonitoring, startRec]);
685
- const stopRecording = useCallback4(async () => {
686
- let buffer;
687
- try {
688
- buffer = await stopRec();
689
- } catch (err) {
690
- setHookError(err instanceof Error ? err : new Error(String(err)));
691
- return;
692
- } finally {
773
+ }, [arrangement]);
774
+ const finishTake = useCallback4(
775
+ (buffer) => {
776
+ if (!buffer) return;
777
+ const trackId = recordingTrackIdRef.current;
778
+ recordingTrackIdRef.current = null;
693
779
  setRecordingTrackId(null);
694
- }
695
- const trackId = recordingTrackIdRef.current;
696
- if (buffer && trackId) {
780
+ if (!trackId) return;
697
781
  if (!arrangement.getTracks().some((t) => t.id === trackId)) {
698
782
  const err = new Error(
699
783
  `Recording completed but track "${trackId}" no longer exists. The recorded audio could not be saved.`
@@ -739,19 +823,19 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
739
823
  console.warn(`[waveform-playlist] ${notSaved.message}`);
740
824
  setHookError(notSaved);
741
825
  }
826
+ },
827
+ [arrangement, latencyOffset]
828
+ );
829
+ finishTakeRef.current = finishTake;
830
+ const stopRecording = useCallback4(async () => {
831
+ let buffer = null;
832
+ try {
833
+ buffer = await stopRec();
834
+ } catch (err) {
835
+ setHookError(err instanceof Error ? err : new Error(String(err)));
742
836
  }
743
- }, [arrangement, stopRec, latencyOffset]);
744
- useEffect4(() => {
745
- if (!hasPermission || devices.length === 0) return;
746
- if (selectedDevice === null) {
747
- setSelectedDevice(devices[0].deviceId);
748
- } else if (!devices.some((d) => d.deviceId === selectedDevice)) {
749
- const fallbackId = devices[0].deviceId;
750
- setSelectedDevice(fallbackId);
751
- resetPeak();
752
- requestAccess(fallbackId, audioConstraints);
753
- }
754
- }, [hasPermission, devices, selectedDevice, resetPeak, requestAccess, audioConstraints]);
837
+ finishTakeRef.current(buffer);
838
+ }, [stopRec]);
755
839
  const isRecordingRef = useRef4(isRecording);
756
840
  isRecordingRef.current = isRecording;
757
841
  const requestMicAccess = useCallback4(async () => {
@@ -761,13 +845,13 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
761
845
  }
762
846
  try {
763
847
  setHookError(null);
764
- await requestAccess(void 0, audioConstraints);
848
+ await requestAccess(void 0, audioConstraintsRef.current);
765
849
  await resumeGlobalAudioContext();
766
- setIsMonitoring(true);
850
+ audioResumedRef.current = true;
767
851
  } catch (err) {
768
852
  setHookError(err instanceof Error ? err : new Error(String(err)));
769
853
  }
770
- }, [requestAccess, audioConstraints]);
854
+ }, [requestAccess]);
771
855
  const changeDevice = useCallback4(
772
856
  async (deviceId) => {
773
857
  if (isRecordingRef.current) {
@@ -776,16 +860,15 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
776
860
  }
777
861
  try {
778
862
  setHookError(null);
779
- setSelectedDevice(deviceId);
780
863
  resetPeak();
781
- await requestAccess(deviceId, audioConstraints);
864
+ await requestAccess(deviceId, audioConstraintsRef.current);
782
865
  await resumeGlobalAudioContext();
783
- setIsMonitoring(true);
866
+ audioResumedRef.current = true;
784
867
  } catch (err) {
785
868
  setHookError(err instanceof Error ? err : new Error(String(err)));
786
869
  }
787
870
  },
788
- [requestAccess, audioConstraints, resetPeak]
871
+ [requestAccess, resetPeak]
789
872
  );
790
873
  return {
791
874
  // Recording state
@@ -800,6 +883,7 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
800
883
  // Microphone state
801
884
  stream,
802
885
  devices,
886
+ hasLabels,
803
887
  hasPermission,
804
888
  selectedDevice,
805
889
  // Recording controls
@@ -811,6 +895,10 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
811
895
  changeDevice
812
896
  };
813
897
  }
898
+ function openDeviceId(stream) {
899
+ const track = stream?.getAudioTracks()[0];
900
+ return track?.getSettings?.().deviceId || null;
901
+ }
814
902
 
815
903
  // src/hooks/useRecordingProgress.ts
816
904
  import { useThrottledValue } from "@waveform-playlist/ui-components";