canvas-recorder-lib 0.6.0 → 0.7.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/BREAKING-CHANGES.md +6 -0
- package/README.md +37 -23
- package/dev/audio-builder.ts +69 -163
- package/dev/canvas-recorder.ts +333 -167
- package/dev/player-body.ts +8 -0
- package/dev/sound-clips.ts +3 -2
- package/dev/soundtrack.ts +434 -0
- package/dev/video-clip-panel.ts +1 -1
- package/dev/voice/chirp.ts +129 -0
- package/dev/voice/folder.ts +84 -0
- package/dev/voice/voice-panel.ts +513 -0
- package/dev/voice/voice-recorder.ts +603 -0
- package/dist/dev/audio-builder.d.ts +14 -31
- package/dist/dev/audio-builder.d.ts.map +1 -1
- package/dist/dev/audio-builder.js +62 -135
- package/dist/dev/audio-builder.js.map +1 -1
- package/dist/dev/canvas-recorder.js +320 -154
- package/dist/dev/canvas-recorder.js.map +1 -1
- package/dist/dev/player-body.d.ts +1 -1
- package/dist/dev/player-body.d.ts.map +1 -1
- package/dist/dev/player-body.js +8 -0
- package/dist/dev/player-body.js.map +1 -1
- package/dist/dev/sound-clips.d.ts +3 -2
- package/dist/dev/sound-clips.d.ts.map +1 -1
- package/dist/dev/sound-clips.js +3 -2
- package/dist/dev/sound-clips.js.map +1 -1
- package/dist/dev/soundtrack.d.ts +115 -0
- package/dist/dev/soundtrack.d.ts.map +1 -0
- package/dist/dev/soundtrack.js +369 -0
- package/dist/dev/soundtrack.js.map +1 -0
- package/dist/dev/video-clip-panel.js +1 -1
- package/dist/dev/video-clip-panel.js.map +1 -1
- package/dist/dev/voice/chirp.d.ts +27 -0
- package/dist/dev/voice/chirp.d.ts.map +1 -0
- package/dist/dev/voice/chirp.js +107 -0
- package/dist/dev/voice/chirp.js.map +1 -0
- package/dist/dev/voice/folder.d.ts +18 -0
- package/dist/dev/voice/folder.d.ts.map +1 -0
- package/dist/dev/voice/folder.js +68 -0
- package/dist/dev/voice/folder.js.map +1 -0
- package/dist/dev/voice/voice-panel.d.ts +44 -0
- package/dist/dev/voice/voice-panel.d.ts.map +1 -0
- package/dist/dev/voice/voice-panel.js +418 -0
- package/dist/dev/voice/voice-panel.js.map +1 -0
- package/dist/dev/voice/voice-recorder.d.ts +141 -0
- package/dist/dev/voice/voice-recorder.d.ts.map +1 -0
- package/dist/dev/voice/voice-recorder.js +506 -0
- package/dist/dev/voice/voice-recorder.js.map +1 -0
- package/dist/src/showable.d.ts +9 -0
- package/dist/src/showable.d.ts.map +1 -1
- package/dist/src/showable.js.map +1 -1
- package/dist/src/snapshot.d.ts.map +1 -1
- package/dist/src/snapshot.js +27 -11
- package/dist/src/snapshot.js.map +1 -1
- package/package.json +1 -1
- package/src/showable.ts +9 -0
- package/src/snapshot.ts +30 -15
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The voice recorder's engine: the mic, the files, and the chirp. No user interface; see
|
|
3
|
+
* voice-panel.ts. Nothing here knows about the player, except that it shares the player's
|
|
4
|
+
* AudioContext.
|
|
5
|
+
*
|
|
6
|
+
* Sharing the AudioContext means sharing its clock, the one the video plays by. An AudioWorklet
|
|
7
|
+
* copies the mic's samples, and says exactly which frame of that clock each one belongs to. So a
|
|
8
|
+
* clip's place in the video is exact, with no clocks to match up.
|
|
9
|
+
*
|
|
10
|
+
* - A **session** runs from ● Record to the stop. It starts with the chirp.
|
|
11
|
+
* - A session holds one or more **clips**. The player starts one whenever the video starts moving,
|
|
12
|
+
* and ends it whenever the video stops or jumps. So a seek ends one clip and starts the next.
|
|
13
|
+
* - Each clip is its own WAV file (32-bit float, mono, 48 kHz), written as it goes, and kept in memory
|
|
14
|
+
* too. The file holds a little more than the clip at each end: the chirp, or what came between
|
|
15
|
+
* two clips, at the start, and {@link TAIL_S} at the end. The clip's trim hides the extra.
|
|
16
|
+
*
|
|
17
|
+
* Copied from riemann-surfaces-3d's src/recording/voice-recorder.ts (9bbe2f9), without the log or
|
|
18
|
+
* the Stop and Marker sounds. See development-plans/voice-recording.md.
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
/** The browser's voice processing. Each one is a checkbox. */
|
|
22
|
+
export declare const PROCESSING: readonly [{
|
|
23
|
+
readonly name: "echoCancellation";
|
|
24
|
+
readonly label: "Echo cancellation";
|
|
25
|
+
readonly help: "For calls. Removes whatever your own speakers are playing. It would erase the chirp.";
|
|
26
|
+
}, {
|
|
27
|
+
readonly name: "noiseSuppression";
|
|
28
|
+
readonly label: "Noise suppression";
|
|
29
|
+
readonly help: "Removes steady background noise, like fans and hum, and some clicks.";
|
|
30
|
+
}, {
|
|
31
|
+
readonly name: "autoGainControl";
|
|
32
|
+
readonly label: "Automatic gain control";
|
|
33
|
+
readonly help: "Turns the volume up and down to keep your voice level. It turns background noise up during your pauses.";
|
|
34
|
+
}, {
|
|
35
|
+
readonly name: "voiceIsolation";
|
|
36
|
+
readonly label: "Voice isolation";
|
|
37
|
+
readonly help: "Only in newer browsers. Tries to keep your voice and nothing else.";
|
|
38
|
+
}];
|
|
39
|
+
export type ProcessingName = (typeof PROCESSING)[number]["name"];
|
|
40
|
+
export type ProcessingChoices = Partial<Record<ProcessingName, boolean>>;
|
|
41
|
+
/** Noise suppression on, the rest off. From riemann's feedback: "The helicopter is gone." */
|
|
42
|
+
export declare const DEFAULT_PROCESSING: ProcessingChoices;
|
|
43
|
+
/** The parts of PROCESSING that this browser offers. */
|
|
44
|
+
export declare function supportedProcessing(): ({
|
|
45
|
+
readonly name: "echoCancellation";
|
|
46
|
+
readonly label: "Echo cancellation";
|
|
47
|
+
readonly help: "For calls. Removes whatever your own speakers are playing. It would erase the chirp.";
|
|
48
|
+
} | {
|
|
49
|
+
readonly name: "noiseSuppression";
|
|
50
|
+
readonly label: "Noise suppression";
|
|
51
|
+
readonly help: "Removes steady background noise, like fans and hum, and some clicks.";
|
|
52
|
+
} | {
|
|
53
|
+
readonly name: "autoGainControl";
|
|
54
|
+
readonly label: "Automatic gain control";
|
|
55
|
+
readonly help: "Turns the volume up and down to keep your voice level. It turns background noise up during your pauses.";
|
|
56
|
+
} | {
|
|
57
|
+
readonly name: "voiceIsolation";
|
|
58
|
+
readonly label: "Voice isolation";
|
|
59
|
+
readonly help: "Only in newer browsers. Tries to keep your voice and nothing else.";
|
|
60
|
+
})[];
|
|
61
|
+
export type HeardResult = {
|
|
62
|
+
/** Undefined if the chirp wasn't found: speakers off, or headphones. */
|
|
63
|
+
roundTripMs?: number;
|
|
64
|
+
match: number;
|
|
65
|
+
peakDb: number;
|
|
66
|
+
};
|
|
67
|
+
/** A finished clip: its file, and the part of the file that goes in the video. */
|
|
68
|
+
export type RecordedClip = {
|
|
69
|
+
/** The file's `local:` URL. */
|
|
70
|
+
readonly url: string;
|
|
71
|
+
/** The whole file, mono, at {@link SAMPLE_RATE}. For `Soundtrack.provide()`. */
|
|
72
|
+
readonly buffer: AudioBuffer;
|
|
73
|
+
/** Where in the file the clip starts, in ms. */
|
|
74
|
+
readonly trimMs: number;
|
|
75
|
+
/** How long the clip is, in ms. */
|
|
76
|
+
readonly lengthMs: number;
|
|
77
|
+
};
|
|
78
|
+
/** The clip being recorded now, for the live waveform. */
|
|
79
|
+
export type LiveClip = {
|
|
80
|
+
/** The file so far. It's longer than the recording: it grows by doubling. */
|
|
81
|
+
readonly buffer: AudioBuffer;
|
|
82
|
+
/** Where in `buffer` the clip starts, in ms. */
|
|
83
|
+
readonly trimMs: number;
|
|
84
|
+
/** How long the clip is so far, in ms. */
|
|
85
|
+
readonly lengthMs: number;
|
|
86
|
+
};
|
|
87
|
+
export declare class VoiceRecorder {
|
|
88
|
+
#private;
|
|
89
|
+
readonly context: AudioContext;
|
|
90
|
+
/** How long the mic and the OS take to deliver a sound, in ms. Measured by the chirp. */
|
|
91
|
+
micDelayMs: number;
|
|
92
|
+
/** Called for each block of audio, about 23 times a second, with levels from 0 to 1. */
|
|
93
|
+
onLevel?: (peak: number, rms: number) => void;
|
|
94
|
+
/** Called when the chirp is found in the recording, or isn't. */
|
|
95
|
+
onHeard?: (result: HeardResult) => void;
|
|
96
|
+
private constructor();
|
|
97
|
+
/**
|
|
98
|
+
* Turn on the mic. Call this from a click, so the browser lets the audio start.
|
|
99
|
+
* The browser asks for permission to use the mic the first time.
|
|
100
|
+
*/
|
|
101
|
+
static open(context: AudioContext, choices: ProcessingChoices): Promise<VoiceRecorder>;
|
|
102
|
+
/** What the mic actually got. The browser can quietly ignore a request. */
|
|
103
|
+
actualSettings(): Record<string, unknown>;
|
|
104
|
+
/** The mic's name, like "MacBook Pro Microphone". */
|
|
105
|
+
get micName(): string;
|
|
106
|
+
/**
|
|
107
|
+
* Turn one kind of voice processing on or off. Works in the middle of a recording. First try
|
|
108
|
+
* changing the mic that's already open. If the browser won't, open the mic again. The recording
|
|
109
|
+
* keeps going, on the same clock, with maybe a moment of silence.
|
|
110
|
+
*/
|
|
111
|
+
setProcessing(name: ProcessingName, on: boolean): Promise<void>;
|
|
112
|
+
/** True from {@link start} to {@link stop}. */
|
|
113
|
+
get recording(): boolean;
|
|
114
|
+
/**
|
|
115
|
+
* Start a session: play the chirp, and start recording.
|
|
116
|
+
* Resolves a moment after the chirp, when the video should start.
|
|
117
|
+
*
|
|
118
|
+
* @param prefix The start of each file's name, usually the video's name.
|
|
119
|
+
*/
|
|
120
|
+
start(folder: FileSystemDirectoryHandle, prefix: string): Promise<void>;
|
|
121
|
+
/**
|
|
122
|
+
* The video started moving at `contextTime`, on the AudioContext's clock.
|
|
123
|
+
* Resolves when the clip's file is finished and on the `local:` list: {@link TAIL_S} after
|
|
124
|
+
* {@link endClip}. Does nothing (and never resolves) outside a session.
|
|
125
|
+
*/
|
|
126
|
+
beginClip(contextTime: number): Promise<RecordedClip>;
|
|
127
|
+
/** The video stopped or jumped at `contextTime`. Does nothing if no clip is being recorded. */
|
|
128
|
+
endClip(contextTime: number): void;
|
|
129
|
+
/** The clip being recorded now, if there is one. */
|
|
130
|
+
liveClip(): LiveClip | undefined;
|
|
131
|
+
/** End the session. Any clip ends now; its file finishes {@link TAIL_S} later. */
|
|
132
|
+
stop(): void;
|
|
133
|
+
/**
|
|
134
|
+
* Finish every file now, without waiting for the tails. For a page that's closing.
|
|
135
|
+
* Each write still has to reach the disk, so this may not finish in time.
|
|
136
|
+
*/
|
|
137
|
+
flush(): void;
|
|
138
|
+
/** Turn off the mic. Stops recording first, and waits a little for the files to finish. */
|
|
139
|
+
close(): Promise<void>;
|
|
140
|
+
}
|
|
141
|
+
//# sourceMappingURL=voice-recorder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"voice-recorder.d.ts","sourceRoot":"","sources":["../../../dev/voice/voice-recorder.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,+DAA+D;AAC/D,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;EAqBb,CAAC;AACX,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;AACjE,MAAM,MAAM,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC,CAAC;AAEzE,+FAA+F;AAC/F,eAAO,MAAM,kBAAkB,EAAE,iBAA8C,CAAC;AAEhF,wDAAwD;AACxD,wBAAgB,mBAAmB;;;;;;;;;;;;;;;;KAMlC;AAkFD,MAAM,MAAM,WAAW,GAAG;IACxB,yEAAyE;IACzE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,mFAAmF;AACnF,MAAM,MAAM,YAAY,GAAG;IACzB,+BAA+B;IAC/B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,iFAAiF;IACjF,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,gDAAgD;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,mCAAmC;IACnC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF,0DAA0D;AAC1D,MAAM,MAAM,QAAQ,GAAG;IACrB,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,gDAAgD;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,0CAA0C;IAC1C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B,CAAC;AA6CF,qBAAa,aAAa;;IACxB,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAC;IAU/B,0FAA0F;IAC1F,UAAU,EAAE,MAAM,CAAC;IACnB,wFAAwF;IACxF,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9C,iEAAiE;IACjE,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,CAAC;IAExC,OAAO;IAaP;;;OAGG;WACU,IAAI,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,aAAa,CAAC;IA0C5F,4EAA4E;IAC5E,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIzC,qDAAqD;IACrD,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED;;;;OAIG;IACG,aAAa,CAAC,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBrE,+CAA+C;IAC/C,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED;;;;;OAKG;IACG,KAAK,CAAC,MAAM,EAAE,yBAAyB,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAyB7E;;;;OAIG;IACH,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IASrD,gGAAgG;IAChG,OAAO,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI;IAYlC,oDAAoD;IACpD,QAAQ,IAAI,QAAQ,GAAG,SAAS;IAWhC,mFAAmF;IACnF,IAAI,IAAI,IAAI;IASZ;;;OAGG;IACH,KAAK,IAAI,IAAI;IAKb,4FAA4F;IACtF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAyJ7B"}
|
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import { addLocalFile } from "../../src/local-files.js";
|
|
2
|
+
import { SAMPLE_RATE } from "../soundtrack.js";
|
|
3
|
+
import { chirpSamples, findSound } from "./chirp.js";
|
|
4
|
+
/**
|
|
5
|
+
* The voice recorder's engine: the mic, the files, and the chirp. No user interface; see
|
|
6
|
+
* voice-panel.ts. Nothing here knows about the player, except that it shares the player's
|
|
7
|
+
* AudioContext.
|
|
8
|
+
*
|
|
9
|
+
* Sharing the AudioContext means sharing its clock, the one the video plays by. An AudioWorklet
|
|
10
|
+
* copies the mic's samples, and says exactly which frame of that clock each one belongs to. So a
|
|
11
|
+
* clip's place in the video is exact, with no clocks to match up.
|
|
12
|
+
*
|
|
13
|
+
* - A **session** runs from ● Record to the stop. It starts with the chirp.
|
|
14
|
+
* - A session holds one or more **clips**. The player starts one whenever the video starts moving,
|
|
15
|
+
* and ends it whenever the video stops or jumps. So a seek ends one clip and starts the next.
|
|
16
|
+
* - Each clip is its own WAV file (32-bit float, mono, 48 kHz), written as it goes, and kept in memory
|
|
17
|
+
* too. The file holds a little more than the clip at each end: the chirp, or what came between
|
|
18
|
+
* two clips, at the start, and {@link TAIL_S} at the end. The clip's trim hides the extra.
|
|
19
|
+
*
|
|
20
|
+
* Copied from riemann-surfaces-3d's src/recording/voice-recorder.ts (9bbe2f9), without the log or
|
|
21
|
+
* the Stop and Marker sounds. See development-plans/voice-recording.md.
|
|
22
|
+
* @module
|
|
23
|
+
*/
|
|
24
|
+
/** The browser's voice processing. Each one is a checkbox. */
|
|
25
|
+
export const PROCESSING = [
|
|
26
|
+
{
|
|
27
|
+
name: "echoCancellation",
|
|
28
|
+
label: "Echo cancellation",
|
|
29
|
+
help: "For calls. Removes whatever your own speakers are playing. It would erase the chirp.",
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
name: "noiseSuppression",
|
|
33
|
+
label: "Noise suppression",
|
|
34
|
+
help: "Removes steady background noise, like fans and hum, and some clicks.",
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: "autoGainControl",
|
|
38
|
+
label: "Automatic gain control",
|
|
39
|
+
help: "Turns the volume up and down to keep your voice level. It turns background noise up during your pauses.",
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
name: "voiceIsolation",
|
|
43
|
+
label: "Voice isolation",
|
|
44
|
+
help: "Only in newer browsers. Tries to keep your voice and nothing else.",
|
|
45
|
+
},
|
|
46
|
+
];
|
|
47
|
+
/** Noise suppression on, the rest off. From riemann's feedback: "The helicopter is gone." */
|
|
48
|
+
export const DEFAULT_PROCESSING = { noiseSuppression: true };
|
|
49
|
+
/** The parts of PROCESSING that this browser offers. */
|
|
50
|
+
export function supportedProcessing() {
|
|
51
|
+
const supported = navigator.mediaDevices.getSupportedConstraints();
|
|
52
|
+
return PROCESSING.filter(({ name }) => supported[name]);
|
|
53
|
+
}
|
|
54
|
+
/** How far ahead to schedule the chirp, in seconds, so it's sure to land inside the recording. */
|
|
55
|
+
const CHIRP_LEAD_S = 0.25;
|
|
56
|
+
/**
|
|
57
|
+
* How long after the chirp ends the video starts, in seconds. The chirp reaches the mic about a
|
|
58
|
+
* tenth of a second after it's played, and the clip starts after that.
|
|
59
|
+
*/
|
|
60
|
+
const AFTER_CHIRP_S = 0.15;
|
|
61
|
+
/** Look for the chirp from a little before it was played to this long after, in seconds. */
|
|
62
|
+
const SEARCH_AFTER_S = 0.3;
|
|
63
|
+
/** A match better than this means the chirp really was heard. Noise scores about 0.03, speech up to about 0.08. */
|
|
64
|
+
const HEARD = 0.15;
|
|
65
|
+
/** How much more than the clip each file holds at the end, in seconds. In case Pause cut off a word. */
|
|
66
|
+
const TAIL_S = 0.5;
|
|
67
|
+
/**
|
|
68
|
+
* How long the mic and the OS take to deliver a sound, until the chirp measures it.
|
|
69
|
+
* Measured on a MacBook Air: a 106 ms round trip, less Chrome's 34 ms output.
|
|
70
|
+
*/
|
|
71
|
+
const DEFAULT_DELAY_MS = 72;
|
|
72
|
+
const DELAY_KEY = "voice-recorder.mic-delay-ms";
|
|
73
|
+
/**
|
|
74
|
+
* The AudioWorklet. It runs on the audio thread, and sends the mic's samples to the page in blocks of
|
|
75
|
+
* 2048, with the clock frame of the first one, and the levels for the meter. It's a string, so it
|
|
76
|
+
* needs no build setup.
|
|
77
|
+
*/
|
|
78
|
+
const WORKLET = /* js */ `
|
|
79
|
+
class VoiceRecorderProcessor extends AudioWorkletProcessor {
|
|
80
|
+
constructor() {
|
|
81
|
+
super();
|
|
82
|
+
this.reset();
|
|
83
|
+
}
|
|
84
|
+
reset() {
|
|
85
|
+
this.samples = new Float32Array(2048);
|
|
86
|
+
this.filled = 0;
|
|
87
|
+
this.peak = 0;
|
|
88
|
+
this.squares = 0;
|
|
89
|
+
}
|
|
90
|
+
process(inputs) {
|
|
91
|
+
const channels = inputs[0];
|
|
92
|
+
const length = channels.length ? channels[0].length : 128;
|
|
93
|
+
if (this.filled + length > this.samples.length) {
|
|
94
|
+
this.send();
|
|
95
|
+
}
|
|
96
|
+
if (this.filled == 0) {
|
|
97
|
+
this.first = currentFrame;
|
|
98
|
+
}
|
|
99
|
+
for (let i = 0; i < length; i++) {
|
|
100
|
+
// Mono. Average the channels if there's more than one.
|
|
101
|
+
let v = 0;
|
|
102
|
+
for (const channel of channels) {
|
|
103
|
+
v += channel[i];
|
|
104
|
+
}
|
|
105
|
+
if (channels.length > 1) {
|
|
106
|
+
v /= channels.length;
|
|
107
|
+
}
|
|
108
|
+
this.samples[this.filled + i] = v;
|
|
109
|
+
this.peak = Math.max(this.peak, Math.abs(v));
|
|
110
|
+
this.squares += v * v;
|
|
111
|
+
}
|
|
112
|
+
this.filled += length;
|
|
113
|
+
if (this.filled == this.samples.length) {
|
|
114
|
+
this.send();
|
|
115
|
+
}
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
send() {
|
|
119
|
+
const samples = this.samples.subarray(0, this.filled);
|
|
120
|
+
const rms = Math.sqrt(this.squares / Math.max(1, this.filled));
|
|
121
|
+
this.port.postMessage({ first: this.first, samples, peak: this.peak, rms }, [this.samples.buffer]);
|
|
122
|
+
this.reset();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
registerProcessor("voice-recorder", VoiceRecorderProcessor);
|
|
126
|
+
`;
|
|
127
|
+
/** addModule() for each context only once: registering the processor twice is an error. */
|
|
128
|
+
const workletLoaded = new WeakMap();
|
|
129
|
+
/** A file name made from the video's name and the time, like `my-video 2026-11-07 14-05-33.250.wav`. */
|
|
130
|
+
function fileName(prefix, now) {
|
|
131
|
+
const pad = (n, width = 2) => String(n).padStart(width, "0");
|
|
132
|
+
const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
|
133
|
+
const time = `${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`;
|
|
134
|
+
// No colons or slashes: Windows doesn't allow them, and the Finder shows a colon as a slash.
|
|
135
|
+
const safe = prefix.replace(/[\\/:*?"<>|]/g, "-");
|
|
136
|
+
return `${safe} ${date} ${time}.wav`;
|
|
137
|
+
}
|
|
138
|
+
export class VoiceRecorder {
|
|
139
|
+
context;
|
|
140
|
+
#node;
|
|
141
|
+
#source;
|
|
142
|
+
#stream;
|
|
143
|
+
#choices;
|
|
144
|
+
#session;
|
|
145
|
+
/** Every file still receiving samples: the current one, and any finishing their tails. */
|
|
146
|
+
#files = new Set();
|
|
147
|
+
/** The chirp, while we wait to find it. */
|
|
148
|
+
#listening;
|
|
149
|
+
/** How long the mic and the OS take to deliver a sound, in ms. Measured by the chirp. */
|
|
150
|
+
micDelayMs;
|
|
151
|
+
/** Called for each block of audio, about 23 times a second, with levels from 0 to 1. */
|
|
152
|
+
onLevel;
|
|
153
|
+
/** Called when the chirp is found in the recording, or isn't. */
|
|
154
|
+
onHeard;
|
|
155
|
+
constructor(context, node, choices) {
|
|
156
|
+
this.context = context;
|
|
157
|
+
this.#node = node;
|
|
158
|
+
this.#choices = choices;
|
|
159
|
+
const saved = Number(localStorage.getItem(DELAY_KEY));
|
|
160
|
+
this.micDelayMs = saved > 0 ? saved : DEFAULT_DELAY_MS;
|
|
161
|
+
node.port.onmessage = (event) => this.#receive(event.data);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Turn on the mic. Call this from a click, so the browser lets the audio start.
|
|
165
|
+
* The browser asks for permission to use the mic the first time.
|
|
166
|
+
*/
|
|
167
|
+
static async open(context, choices) {
|
|
168
|
+
await workletLoaded.getOrInsertComputed(context, async () => {
|
|
169
|
+
const url = URL.createObjectURL(new Blob([WORKLET], { type: "text/javascript" }));
|
|
170
|
+
try {
|
|
171
|
+
await context.audioWorklet.addModule(url);
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
URL.revokeObjectURL(url);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
const node = new AudioWorkletNode(context, "voice-recorder");
|
|
178
|
+
// An audio node only runs if it leads to the speakers. The worklet never writes anything to its
|
|
179
|
+
// output, so this is silent.
|
|
180
|
+
node.connect(context.destination);
|
|
181
|
+
const recorder = new VoiceRecorder(context, node, choices);
|
|
182
|
+
try {
|
|
183
|
+
await recorder.#connectMic();
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
node.disconnect();
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
await context.resume();
|
|
190
|
+
return recorder;
|
|
191
|
+
}
|
|
192
|
+
#constraints() {
|
|
193
|
+
const result = { channelCount: { ideal: 1 } };
|
|
194
|
+
for (const { name } of supportedProcessing()) {
|
|
195
|
+
result[name] = this.#choices[name] ?? false;
|
|
196
|
+
}
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
199
|
+
async #connectMic() {
|
|
200
|
+
this.#stream = await navigator.mediaDevices.getUserMedia({ audio: this.#constraints() });
|
|
201
|
+
this.#source = new MediaStreamAudioSourceNode(this.context, { mediaStream: this.#stream });
|
|
202
|
+
this.#source.connect(this.#node);
|
|
203
|
+
}
|
|
204
|
+
get #track() {
|
|
205
|
+
return this.#stream?.getAudioTracks()[0];
|
|
206
|
+
}
|
|
207
|
+
/** What the mic actually got. The browser can quietly ignore a request. */
|
|
208
|
+
actualSettings() {
|
|
209
|
+
return (this.#track?.getSettings() ?? {});
|
|
210
|
+
}
|
|
211
|
+
/** The mic's name, like "MacBook Pro Microphone". */
|
|
212
|
+
get micName() {
|
|
213
|
+
return this.#track?.label ?? "";
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Turn one kind of voice processing on or off. Works in the middle of a recording. First try
|
|
217
|
+
* changing the mic that's already open. If the browser won't, open the mic again. The recording
|
|
218
|
+
* keeps going, on the same clock, with maybe a moment of silence.
|
|
219
|
+
*/
|
|
220
|
+
async setProcessing(name, on) {
|
|
221
|
+
this.#choices = { ...this.#choices, [name]: on };
|
|
222
|
+
try {
|
|
223
|
+
await this.#track?.applyConstraints(this.#constraints());
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
// Handled below.
|
|
227
|
+
}
|
|
228
|
+
if (this.actualSettings()[name] !== on) {
|
|
229
|
+
const old = this.#source;
|
|
230
|
+
this.#stream?.getTracks().forEach((track) => track.stop());
|
|
231
|
+
old?.disconnect();
|
|
232
|
+
await this.#connectMic();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
// MARK: Sessions and clips
|
|
236
|
+
/** True from {@link start} to {@link stop}. */
|
|
237
|
+
get recording() {
|
|
238
|
+
return this.#session !== undefined;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Start a session: play the chirp, and start recording.
|
|
242
|
+
* Resolves a moment after the chirp, when the video should start.
|
|
243
|
+
*
|
|
244
|
+
* @param prefix The start of each file's name, usually the video's name.
|
|
245
|
+
*/
|
|
246
|
+
async start(folder, prefix) {
|
|
247
|
+
if (this.#session)
|
|
248
|
+
return;
|
|
249
|
+
await this.context.resume();
|
|
250
|
+
const chirp = chirpSamples(SAMPLE_RATE);
|
|
251
|
+
const when = this.context.currentTime + CHIRP_LEAD_S;
|
|
252
|
+
const chirpFrame = Math.round(when * SAMPLE_RATE);
|
|
253
|
+
const session = { folder, prefix, nextStartFrame: chirpFrame };
|
|
254
|
+
this.#session = session;
|
|
255
|
+
// The first file starts with the chirp.
|
|
256
|
+
const file = this.#openFile(session, chirpFrame);
|
|
257
|
+
session.current = file;
|
|
258
|
+
this.#listening = { file, samples: chirp };
|
|
259
|
+
// Straight to the speakers, so the player's mute doesn't silence it.
|
|
260
|
+
const buffer = new AudioBuffer({ numberOfChannels: 1, length: chirp.length, sampleRate: SAMPLE_RATE });
|
|
261
|
+
buffer.copyToChannel(chirp, 0);
|
|
262
|
+
const node = new AudioBufferSourceNode(this.context, { buffer });
|
|
263
|
+
node.connect(this.context.destination);
|
|
264
|
+
node.onended = () => node.disconnect();
|
|
265
|
+
node.start(when);
|
|
266
|
+
const videoStarts = when + buffer.duration + AFTER_CHIRP_S;
|
|
267
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(0, videoStarts - this.context.currentTime) * 1000));
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* The video started moving at `contextTime`, on the AudioContext's clock.
|
|
271
|
+
* Resolves when the clip's file is finished and on the `local:` list: {@link TAIL_S} after
|
|
272
|
+
* {@link endClip}. Does nothing (and never resolves) outside a session.
|
|
273
|
+
*/
|
|
274
|
+
beginClip(contextTime) {
|
|
275
|
+
const session = this.#session;
|
|
276
|
+
if (!session)
|
|
277
|
+
return new Promise(() => { });
|
|
278
|
+
if (session.current?.clipStart !== undefined)
|
|
279
|
+
this.endClip(contextTime);
|
|
280
|
+
session.current ??= this.#openFile(session, session.nextStartFrame);
|
|
281
|
+
session.current.clipStart = contextTime;
|
|
282
|
+
return session.current.finished;
|
|
283
|
+
}
|
|
284
|
+
/** The video stopped or jumped at `contextTime`. Does nothing if no clip is being recorded. */
|
|
285
|
+
endClip(contextTime) {
|
|
286
|
+
const session = this.#session;
|
|
287
|
+
const file = session?.current;
|
|
288
|
+
if (!session || file?.clipStart === undefined)
|
|
289
|
+
return;
|
|
290
|
+
file.clipEnd = Math.max(file.clipStart, contextTime);
|
|
291
|
+
file.endFrame = Math.round((file.clipEnd + this.micDelayMs / 1000 + TAIL_S) * SAMPLE_RATE);
|
|
292
|
+
session.current = undefined;
|
|
293
|
+
session.nextStartFrame = Math.round(file.clipEnd * SAMPLE_RATE);
|
|
294
|
+
}
|
|
295
|
+
/** The clip being recorded now, if there is one. */
|
|
296
|
+
liveClip() {
|
|
297
|
+
const file = this.#session?.current;
|
|
298
|
+
if (file?.clipStart === undefined)
|
|
299
|
+
return undefined;
|
|
300
|
+
const trimMs = this.#trimMs(file);
|
|
301
|
+
return {
|
|
302
|
+
buffer: file.buffer,
|
|
303
|
+
trimMs,
|
|
304
|
+
lengthMs: Math.max(0, (file.frames / SAMPLE_RATE) * 1000 - trimMs),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
/** End the session. Any clip ends now; its file finishes {@link TAIL_S} later. */
|
|
308
|
+
stop() {
|
|
309
|
+
const session = this.#session;
|
|
310
|
+
if (!session)
|
|
311
|
+
return;
|
|
312
|
+
this.endClip(this.context.currentTime);
|
|
313
|
+
// A file with no clip yet: ■ Stop during the chirp.
|
|
314
|
+
if (session.current)
|
|
315
|
+
void this.#finish(session.current);
|
|
316
|
+
this.#session = undefined;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Finish every file now, without waiting for the tails. For a page that's closing.
|
|
320
|
+
* Each write still has to reach the disk, so this may not finish in time.
|
|
321
|
+
*/
|
|
322
|
+
flush() {
|
|
323
|
+
this.stop();
|
|
324
|
+
for (const file of this.#files)
|
|
325
|
+
void this.#finish(file);
|
|
326
|
+
}
|
|
327
|
+
/** Turn off the mic. Stops recording first, and waits a little for the files to finish. */
|
|
328
|
+
async close() {
|
|
329
|
+
this.stop();
|
|
330
|
+
const files = [...this.#files];
|
|
331
|
+
// The tails need the mic. Wait for them, but not forever.
|
|
332
|
+
await Promise.race([
|
|
333
|
+
Promise.allSettled(files.map((file) => file.finished)),
|
|
334
|
+
new Promise((resolve) => setTimeout(resolve, (TAIL_S + 1) * 1000)),
|
|
335
|
+
]);
|
|
336
|
+
for (const file of files)
|
|
337
|
+
void this.#finish(file);
|
|
338
|
+
this.#stream?.getTracks().forEach((track) => track.stop());
|
|
339
|
+
this.#source?.disconnect();
|
|
340
|
+
this.#node.disconnect();
|
|
341
|
+
}
|
|
342
|
+
// MARK: Files
|
|
343
|
+
#openFile(session, startFrame) {
|
|
344
|
+
const name = fileName(session.prefix, new Date());
|
|
345
|
+
const handle = session.folder.getFileHandle(name, { create: true });
|
|
346
|
+
let resolve;
|
|
347
|
+
let reject;
|
|
348
|
+
const finished = new Promise((res, rej) => {
|
|
349
|
+
resolve = res;
|
|
350
|
+
reject = rej;
|
|
351
|
+
});
|
|
352
|
+
// The player may never use this file (■ Stop during the chirp), and then nobody listens.
|
|
353
|
+
finished.catch(() => { });
|
|
354
|
+
const file = {
|
|
355
|
+
folder: session.folder,
|
|
356
|
+
name,
|
|
357
|
+
startFrame,
|
|
358
|
+
buffer: new AudioBuffer({ numberOfChannels: 1, length: 10 * SAMPLE_RATE, sampleRate: SAMPLE_RATE }),
|
|
359
|
+
frames: 0,
|
|
360
|
+
handle,
|
|
361
|
+
writing: handle
|
|
362
|
+
.then((handle) => handle.createWritable())
|
|
363
|
+
.then(async (stream) => {
|
|
364
|
+
await stream.write(wavHeader(0));
|
|
365
|
+
return stream;
|
|
366
|
+
}),
|
|
367
|
+
finished,
|
|
368
|
+
resolve,
|
|
369
|
+
reject,
|
|
370
|
+
done: false,
|
|
371
|
+
};
|
|
372
|
+
// A failed write is reported once, by #finish().
|
|
373
|
+
file.writing.catch(() => { });
|
|
374
|
+
this.#files.add(file);
|
|
375
|
+
return file;
|
|
376
|
+
}
|
|
377
|
+
/** Where in the file the clip starts, in ms, corrected for the mic's delay. */
|
|
378
|
+
#trimMs(file) {
|
|
379
|
+
const fileStart = file.startFrame / SAMPLE_RATE;
|
|
380
|
+
return ((file.clipStart ?? fileStart) - fileStart) * 1000 + this.micDelayMs;
|
|
381
|
+
}
|
|
382
|
+
/** A block of audio from the worklet. */
|
|
383
|
+
#receive(chunk) {
|
|
384
|
+
this.onLevel?.(chunk.peak, chunk.rms);
|
|
385
|
+
for (const file of this.#files) {
|
|
386
|
+
const from = Math.max(0, file.startFrame - chunk.first);
|
|
387
|
+
const to = Math.min(chunk.samples.length, (file.endFrame ?? Infinity) - chunk.first);
|
|
388
|
+
if (to > from)
|
|
389
|
+
this.#append(file, chunk.samples.subarray(from, to));
|
|
390
|
+
if (file.endFrame !== undefined && chunk.first + chunk.samples.length >= file.endFrame) {
|
|
391
|
+
void this.#finish(file);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
this.#lookForChirp();
|
|
395
|
+
}
|
|
396
|
+
#append(file, samples) {
|
|
397
|
+
const needed = file.frames + samples.length;
|
|
398
|
+
if (needed > file.buffer.length) {
|
|
399
|
+
const bigger = new AudioBuffer({
|
|
400
|
+
numberOfChannels: 1,
|
|
401
|
+
length: Math.max(needed, file.buffer.length * 2),
|
|
402
|
+
sampleRate: SAMPLE_RATE,
|
|
403
|
+
});
|
|
404
|
+
bigger.getChannelData(0).set(file.buffer.getChannelData(0).subarray(0, file.frames));
|
|
405
|
+
file.buffer = bigger;
|
|
406
|
+
}
|
|
407
|
+
file.buffer.getChannelData(0).set(samples, file.frames);
|
|
408
|
+
file.frames = needed;
|
|
409
|
+
const data = samples.slice();
|
|
410
|
+
file.writing = file.writing.then(async (stream) => {
|
|
411
|
+
await stream.write(data);
|
|
412
|
+
return stream;
|
|
413
|
+
});
|
|
414
|
+
file.writing.catch(() => { });
|
|
415
|
+
}
|
|
416
|
+
/** Once enough has arrived, find the chirp, and measure the mic's delay with it. */
|
|
417
|
+
#lookForChirp() {
|
|
418
|
+
const listening = this.#listening;
|
|
419
|
+
if (!listening)
|
|
420
|
+
return;
|
|
421
|
+
const { file, samples } = listening;
|
|
422
|
+
// The file starts when the chirp was played, so a sound that took no time at all would be at 0.
|
|
423
|
+
if (!file.done && file.frames < samples.length + SEARCH_AFTER_S * SAMPLE_RATE)
|
|
424
|
+
return;
|
|
425
|
+
this.#listening = undefined;
|
|
426
|
+
const recording = file.buffer.getChannelData(0).subarray(0, file.frames);
|
|
427
|
+
const found = findSound(recording, samples, 0, SEARCH_AFTER_S * SAMPLE_RATE);
|
|
428
|
+
const heard = found.match > HEARD;
|
|
429
|
+
const result = {
|
|
430
|
+
roundTripMs: heard ? (found.position / SAMPLE_RATE) * 1000 : undefined,
|
|
431
|
+
match: found.match,
|
|
432
|
+
peakDb: found.peakDb,
|
|
433
|
+
};
|
|
434
|
+
if (result.roundTripMs !== undefined) {
|
|
435
|
+
const delayMs = result.roundTripMs - this.context.outputLatency * 1000;
|
|
436
|
+
if (delayMs > 0 && delayMs < 500) {
|
|
437
|
+
this.micDelayMs = delayMs;
|
|
438
|
+
localStorage.setItem(DELAY_KEY, String(delayMs));
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
this.onHeard?.(result);
|
|
442
|
+
}
|
|
443
|
+
/** Close the file, and put it on the `local:` list. Safe to call more than once. */
|
|
444
|
+
async #finish(file) {
|
|
445
|
+
if (file.done)
|
|
446
|
+
return;
|
|
447
|
+
file.done = true;
|
|
448
|
+
this.#files.delete(file);
|
|
449
|
+
// A file that's finished early, like a closing page's, may still hold the chirp's search.
|
|
450
|
+
this.#lookForChirp();
|
|
451
|
+
const frames = file.frames;
|
|
452
|
+
try {
|
|
453
|
+
const stream = await file.writing;
|
|
454
|
+
await stream.write({ type: "write", position: 0, data: wavHeader(frames) });
|
|
455
|
+
await stream.close();
|
|
456
|
+
const handle = await file.handle;
|
|
457
|
+
if (file.clipStart === undefined) {
|
|
458
|
+
// ■ Stop during the chirp: there's no clip.
|
|
459
|
+
await file.folder.removeEntry(file.name).catch(() => { });
|
|
460
|
+
file.reject(new Error("No clip"));
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
const buffer = new AudioBuffer({
|
|
464
|
+
numberOfChannels: 1,
|
|
465
|
+
length: Math.max(1, frames),
|
|
466
|
+
sampleRate: SAMPLE_RATE,
|
|
467
|
+
});
|
|
468
|
+
buffer.copyToChannel(file.buffer.getChannelData(0).subarray(0, frames), 0);
|
|
469
|
+
const trimMs = this.#trimMs(file);
|
|
470
|
+
const lengthMs = ((file.clipEnd ?? file.clipStart) - file.clipStart) * 1000;
|
|
471
|
+
file.resolve({ url: await addLocalFile(handle), buffer, trimMs, lengthMs });
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
file.reject(error);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* The header for a 32-bit float, mono WAV file with this many samples. 58 bytes. It's written as a
|
|
480
|
+
* placeholder first, and again with the real length when the file is finished.
|
|
481
|
+
*/
|
|
482
|
+
function wavHeader(frames) {
|
|
483
|
+
const dataBytes = frames * 4;
|
|
484
|
+
const header = new DataView(new ArrayBuffer(58));
|
|
485
|
+
const text = (at, value) => [...value].forEach((c, i) => header.setUint8(at + i, c.charCodeAt(0)));
|
|
486
|
+
text(0, "RIFF");
|
|
487
|
+
header.setUint32(4, 50 + dataBytes, true);
|
|
488
|
+
text(8, "WAVE");
|
|
489
|
+
text(12, "fmt ");
|
|
490
|
+
header.setUint32(16, 18, true);
|
|
491
|
+
// 3 is IEEE float.
|
|
492
|
+
header.setUint16(20, 3, true);
|
|
493
|
+
header.setUint16(22, 1, true);
|
|
494
|
+
header.setUint32(24, SAMPLE_RATE, true);
|
|
495
|
+
header.setUint32(28, SAMPLE_RATE * 4, true);
|
|
496
|
+
header.setUint16(32, 4, true);
|
|
497
|
+
header.setUint16(34, 32, true);
|
|
498
|
+
header.setUint16(36, 0, true);
|
|
499
|
+
text(38, "fact");
|
|
500
|
+
header.setUint32(42, 4, true);
|
|
501
|
+
header.setUint32(46, frames, true);
|
|
502
|
+
text(50, "data");
|
|
503
|
+
header.setUint32(54, dataBytes, true);
|
|
504
|
+
return header.buffer;
|
|
505
|
+
}
|
|
506
|
+
//# sourceMappingURL=voice-recorder.js.map
|