Open History to see the last commit
1import { arrayBufferToBase64 } from '@tanstack/ai-utils'
2import type { AudioPart } from '@tanstack/ai/client'
3
4/** Lifecycle state of an {@link AudioRecorder}. */
5export type AudioRecorderState = 'idle' | 'recording' | 'stopping'
6
7export interface AudioRecorderOptions {
8 /** Constraints forwarded to `getUserMedia({ audio })`. Defaults to `true`. */
9 audio?: MediaTrackConstraints | boolean
10 /**
11 * Preferred recorder mime type. Used only when
12 * `MediaRecorder.isTypeSupported` reports it; otherwise the browser default
13 * is used.
14 */
15 mimeType?: string
16 /** Fired on `getUserMedia` rejection (permission denied) or recorder error. */
17 onError?: (error: Error) => void
18}
19
20/**
21 * Resolves the value `stop()` produces from a recorder transform callback.
22 *
23 * - If the callback returns a value — sync or async — that value's awaited type
24 * is used (a returned `null` is a real value and is preserved).
25 * - If the callback returns nothing (`void`/`undefined`), or is absent, falls
26 * back to {@link AudioRecording}.
27 *
28 * @template TFn - The transform callback type (or undefined if not provided)
29 */
30export type InferAudioRecordingOutput<TFn> = TFn extends (
31 recording: AudioRecording,
32) => infer R
33 ? [Exclude<Awaited<R>, void | undefined>] extends [never]
34 ? AudioRecording
35 : Exclude<Awaited<R>, void | undefined>
36 : AudioRecording
37
38export interface AudioRecording {
39 /** The raw recorded media blob. */
40 blob: Blob
41 /** Base64 of the recorded bytes (no `data:` prefix). */
42 base64: string
43 /** The recorder's native mime type, e.g. `audio/webm;codecs=opus`. */
44 mimeType: string
45 /** Recording length in milliseconds. */
46 durationMs: number
47 /**
48 * Ready-to-use audio content part for `sendMessage`/generation prompts:
49 * `{ type: 'audio', source: { type: 'data', value: base64, mimeType } }`.
50 */
51 part: AudioPart
52}
53
54/**
55 * Framework-agnostic browser audio recorder. Wraps `getUserMedia` +
56 * `MediaRecorder`, returns the recorder's native output (no transcode), and
57 * builds a plug-and-play {@link AudioRecording.part}.
58 */
59export class AudioRecorder {
60 private readonly options: AudioRecorderOptions
61 private recorder: MediaRecorder | null = null
62 private stream: MediaStream | null = null
63 private chunks: Array<Blob> = []
64 private startedAt = 0
65 private _state: AudioRecorderState = 'idle'
66 // True while start() is awaiting getUserMedia (state is still 'idle' then).
67 private starting = false
68 // Set by cancel()/teardown during that window so start() releases the
69 // freshly acquired stream instead of beginning a leaked recording.
70 private pendingCancel = false
71 private readonly listeners = new Set<(state: AudioRecorderState) => void>()
72 private stopResolve: ((recording: AudioRecording) => void) | null = null
73 private stopReject: ((error: Error) => void) | null = null
74
75 constructor(options: AudioRecorderOptions = {}) {
76 this.options = options
77 }
78
79 /** Feature-detect the browser media APIs. SSR/Worker-safe. */
80 static isSupported(): boolean {
81 return (
82 typeof navigator !== 'undefined' &&
83 typeof navigator.mediaDevices !== 'undefined' &&
84 typeof navigator.mediaDevices.getUserMedia === 'function' &&
85 typeof MediaRecorder !== 'undefined'
86 )
87 }
88
89 get state(): AudioRecorderState {
90 return this._state
91 }
92
93 subscribe(cb: (state: AudioRecorderState) => void): () => void {
94 this.listeners.add(cb)
95 return () => {
96 this.listeners.delete(cb)
97 }
98 }
99
100 private setState(state: AudioRecorderState): void {
101 this._state = state
102 for (const cb of this.listeners) {
103 cb(state)
104 }
105 }
106
107 async start(): Promise<void> {
108 if (this._state !== 'idle' || this.starting) {
109 return
110 }
111 this.starting = true
112 try {
113 const stream = await navigator.mediaDevices.getUserMedia({
114 audio: this.options.audio ?? true,
115 })
116 // cancel()/teardown ran while we were awaiting the mic: release the
117 // freshly acquired stream and bail rather than starting a recording the
118 // caller can no longer stop (a leaked live microphone).
119 if (this.pendingCancel) {
120 stream.getTracks().forEach((t) => t.stop())
121 return
122 }
123 this.stream = stream
124 const wanted = this.options.mimeType
125 const useMimeType =
126 wanted &&
127 typeof MediaRecorder.isTypeSupported === 'function' &&
128 MediaRecorder.isTypeSupported(wanted)
129 ? wanted
130 : undefined
131 const recorder = useMimeType
132 ? new MediaRecorder(stream, { mimeType: useMimeType })
133 : new MediaRecorder(stream)
134 this.chunks = []
135 recorder.ondataavailable = (e) => {
136 if (e.data.size > 0) {
137 this.chunks.push(e.data)
138 }
139 }
140 recorder.onstop = () => {
141 void this.finalize()
142 }
143 recorder.onerror = (event) => {
144 const detail =
145 'error' in event && event.error instanceof Error
146 ? event.error
147 : new Error('Audio recording failed')
148 this.handleError(detail)
149 }
150 this.recorder = recorder
151 this.startedAt = Date.now()
152 recorder.start()
153 this.setState('recording')
154 } catch (err) {
155 this.releaseStream()
156 this.recorder = null
157 const error =
158 err instanceof Error ? err : new Error('Failed to start recording')
159 this.setState('idle')
160 this.notifyError(error)
161 throw error
162 } finally {
163 this.starting = false
164 // Reset here (not before the await) so a cancel() that arrives mid-start
165 // is observed above; clearing it afterward keeps the next start() clean.
166 this.pendingCancel = false
167 }
168 }
169
170 stop(): Promise<AudioRecording> {
171 if (this._state !== 'recording' || !this.recorder) {
172 return Promise.reject(
173 new Error('AudioRecorder.stop() called while not recording'),
174 )
175 }
176 this.setState('stopping')
177 const recorder = this.recorder
178 return new Promise<AudioRecording>((resolve, reject) => {
179 // Some browsers/codecs never fire onstop; this watchdog unwedges the
180 // recorder instead of leaking this promise forever.
181 const watchdog = setTimeout(() => {
182 if (this._state !== 'stopping') {
183 return
184 }
185 // Detach handlers so a late onstop/onerror from the stalled recorder
186 // can't reach back in and fire finalize()/onError a second time.
187 this.detachRecorder()
188 if (this.chunks.length > 0) {
189 // onstop never fired, but ondataavailable already delivered the
190 // audio — finalize from the buffered chunks rather than discarding a
191 // recording the user successfully captured.
192 void this.finalize()
193 } else {
194 this.handleError(
195 new Error('Recording stop timed out after 10s with no audio'),
196 )
197 }
198 }, 10_000)
199 this.stopResolve = (rec) => {
200 clearTimeout(watchdog)
201 resolve(rec)
202 }
203 this.stopReject = (err) => {
204 clearTimeout(watchdog)
205 reject(err)
206 }
207 recorder.stop()
208 })
209 }
210
211 cancel(): void {
212 if (this.starting) {
213 // A start() is awaiting getUserMedia; flag it so the resolved stream is
214 // released instead of beginning a recording with no handle to stop it.
215 this.pendingCancel = true
216 return
217 }
218 if (this._state === 'idle') {
219 return
220 }
221 const recorder = this.recorder
222 if (recorder) {
223 // Detach handlers so finalize()/onError never run for a discarded
224 // recording.
225 this.detachRecorder()
226 try {
227 recorder.stop()
228 } catch (err) {
229 // Stopping an already-inactive recorder throws InvalidStateError —
230 // that's expected here. Anything else is unexpected; surface it rather
231 // than swallowing it silently.
232 if (
233 !(err instanceof DOMException && err.name === 'InvalidStateError')
234 ) {
235 this.notifyError(
236 err instanceof Error ? err : new Error('Failed to stop recorder'),
237 )
238 }
239 }
240 }
241 this.releaseStream()
242 this.recorder = null
243 this.chunks = []
244 const reject = this.stopReject
245 this.stopResolve = null
246 this.stopReject = null
247 this.setState('idle')
248 reject?.(new Error('Recording cancelled'))
249 }
250
251 private async finalize(): Promise<void> {
252 const mimeType = this.recorder?.mimeType || 'audio/webm'
253 const durationMs = Date.now() - this.startedAt
254 try {
255 const blob = new Blob(this.chunks, { type: mimeType })
256 const base64 = arrayBufferToBase64(await blob.arrayBuffer())
257 const recording: AudioRecording = {
258 blob,
259 base64,
260 mimeType,
261 durationMs,
262 part: {
263 type: 'audio',
264 source: { type: 'data', value: base64, mimeType },
265 },
266 }
267 this.releaseStream()
268 this.recorder = null
269 this.chunks = []
270 const resolve = this.stopResolve
271 this.stopResolve = null
272 this.stopReject = null
273 this.setState('idle')
274 resolve?.(recording)
275 } catch (err) {
276 this.handleError(
277 err instanceof Error ? err : new Error('Failed to finalize recording'),
278 )
279 }
280 }
281
282 private handleError(error: Error): void {
283 this.releaseStream()
284 this.recorder = null
285 this.chunks = []
286 const reject = this.stopReject
287 this.stopResolve = null
288 this.stopReject = null
289 this.setState('idle')
290 // Settle the pending stop() promise before invoking the user callback so a
291 // throwing onError can't strand the awaiter (the two error channels are
292 // independent — see start()/stop() docs).
293 reject?.(error)
294 this.notifyError(error)
295 }
296
297 /** Invoke the user onError callback, isolating a throw so it can't disrupt
298 * internal state teardown or strand a pending promise. */
299 private notifyError(error: Error): void {
300 try {
301 this.options.onError?.(error)
302 } catch {
303 // A user onError that throws must not propagate into recorder internals.
304 }
305 }
306
307 private releaseStream(): void {
308 this.stream?.getTracks().forEach((t) => t.stop())
309 this.stream = null
310 }
311
312 /** Detach all event handlers so a stale recorder can't mutate our state. */
313 private detachRecorder(): void {
314 const recorder = this.recorder
315 if (!recorder) {
316 return
317 }
318 recorder.onstop = null
319 recorder.onerror = null
320 recorder.ondataavailable = null
321 }
322}