1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
|
/**
* Voice-over recording via MediaRecorder.
* Pure helpers (mime type picking, file extension, elapsed formatting, error
* messages) are exported for unit tests; the recorder singleton below owns the
* actual microphone stream.
*/
export const PREFERRED_MIME_TYPES = [
"audio/webm;codecs=opus",
"audio/webm",
"audio/ogg;codecs=opus",
"audio/ogg",
"audio/mp4",
] as const;
export function pickSupportedMimeType({
isTypeSupported,
candidates = PREFERRED_MIME_TYPES,
}: {
isTypeSupported: (mimeType: string) => boolean;
candidates?: readonly string[];
}): string | null {
for (const mimeType of candidates) {
if (isTypeSupported(mimeType)) {
return mimeType;
}
}
return null;
}
const EXTENSION_BY_MIME_SUBTYPE: Record<string, string> = {
webm: "webm",
ogg: "ogg",
mp4: "m4a",
mpeg: "mp3",
wav: "wav",
};
export function getFileExtensionForMimeType({
mimeType,
}: {
mimeType: string;
}): string {
const subtype = mimeType.split("/").at(1)?.split(";").at(0)?.trim() ?? "";
return EXTENSION_BY_MIME_SUBTYPE[subtype] ?? "audio";
}
export function formatElapsedSeconds({
seconds,
}: {
seconds: number;
}): string {
const totalSeconds = Math.max(0, Math.floor(seconds));
const minutes = Math.floor(totalSeconds / 60);
const remainder = totalSeconds % 60;
return `${minutes}:${String(remainder).padStart(2, "0")}`;
}
export function getVoiceOverErrorMessage({
error,
}: {
error: unknown;
}): string {
if (error instanceof DOMException) {
switch (error.name) {
case "NotAllowedError":
case "SecurityError":
return "Microphone access denied. Allow microphone access in your browser settings to record a voice-over.";
case "NotFoundError":
case "OverconstrainedError":
return "No microphone found. Connect a microphone and try again.";
case "NotReadableError":
return "The microphone is already in use by another application.";
default:
return "Could not start voice-over recording.";
}
}
if (error instanceof Error && error.message) {
return error.message;
}
return "Could not start voice-over recording.";
}
export interface VoiceOverRecordingResult {
blob: Blob;
mimeType: string;
durationSeconds: number;
}
interface ActiveRecording {
recorder: MediaRecorder;
stream: MediaStream;
chunks: Blob[];
mimeType: string;
startedAtMs: number;
}
let activeRecording: ActiveRecording | null = null;
function stopStreamTracks({ stream }: { stream: MediaStream }): void {
for (const track of stream.getTracks()) {
track.stop();
}
}
export async function startVoiceOverRecording(): Promise<void> {
if (activeRecording) {
throw new Error("A voice-over recording is already in progress");
}
const mediaDevices = navigator.mediaDevices;
if (!mediaDevices?.getUserMedia) {
throw new Error("Voice-over recording is not supported in this browser");
}
const stream = await mediaDevices.getUserMedia({ audio: true });
try {
const mimeType = pickSupportedMimeType({
isTypeSupported: (candidate) => MediaRecorder.isTypeSupported(candidate),
});
const recorder = mimeType
? new MediaRecorder(stream, { mimeType })
: new MediaRecorder(stream);
const chunks: Blob[] = [];
recorder.addEventListener("dataavailable", (event) => {
if (event.data.size > 0) {
chunks.push(event.data);
}
});
recorder.start();
activeRecording = {
recorder,
stream,
chunks,
mimeType: recorder.mimeType || mimeType || "audio/webm",
startedAtMs: performance.now(),
};
} catch (error) {
stopStreamTracks({ stream });
throw error;
}
}
export function stopVoiceOverRecording(): Promise<VoiceOverRecordingResult> {
const recording = activeRecording;
if (!recording) {
return Promise.reject(
new Error("No voice-over recording is in progress"),
);
}
activeRecording = null;
const { promise, resolve, reject } =
Promise.withResolvers<VoiceOverRecordingResult>();
recording.recorder.addEventListener("stop", () => {
stopStreamTracks({ stream: recording.stream });
resolve({
blob: new Blob(recording.chunks, { type: recording.mimeType }),
mimeType: recording.mimeType,
durationSeconds: Math.max(
0,
(performance.now() - recording.startedAtMs) / 1000,
),
});
});
recording.recorder.addEventListener("error", () => {
stopStreamTracks({ stream: recording.stream });
reject(new Error("Voice-over recording failed"));
});
recording.recorder.stop();
return promise;
}
export function cancelVoiceOverRecording(): void {
const recording = activeRecording;
if (!recording) {
return;
}
activeRecording = null;
try {
recording.recorder.stop();
} catch {
// recorder may already be stopped; tracks are released either way
}
stopStreamTracks({ stream: recording.stream });
}
|