Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

audio-recorder.ts

323 lines10.4 KB

1import { arrayBufferToBase64 } from '@tanstack/ai-utils'
2import type { AudioPart } from '@tanstack/ai/client'
3import { notifyListeners } from './snapshot-atom'
4​
5/** Lifecycle state of an {@link AudioRecorder}. */
6export type AudioRecorderState = 'idle' | 'recording' | 'stopping'
7​
8export interface AudioRecorderOptions {
9 /** Constraints forwarded to `getUserMedia({ audio })`. Defaults to `true`. */
10 audio?: MediaTrackConstraints | boolean
11 /**
12 * Preferred recorder mime type. Used only when
13 * `MediaRecorder.isTypeSupported` reports it; otherwise the browser default
14 * is used.
15 */
16 mimeType?: string
17 /** Fired on `getUserMedia` rejection (permission denied) or recorder error. */
18 onError?: (error: Error) => void
20​
21/**
22 * Resolves the value `stop()` produces from a recorder transform callback.
23 *
24 * - If the callback returns a value — sync or async — that value's awaited type
25 * is used (a returned `null` is a real value and is preserved).
26 * - If the callback returns nothing (`void`/`undefined`), or is absent, falls
27 * back to {@link AudioRecording}.
28 *
29 * @template TFn - The transform callback type (or undefined if not provided)
30 */
31export type InferAudioRecordingOutput<TFn> = TFn extends (
32 recording: AudioRecording,
33) => infer R
34 ? [Exclude<Awaited<R>, void | undefined>] extends [never]
35 ? AudioRecording
36 : Exclude<Awaited<R>, void | undefined>
37 : AudioRecording
38​
39export interface AudioRecording {
40 /** The raw recorded media blob. */
41 blob: Blob
42 /** Base64 of the recorded bytes (no `data:` prefix). */
43 base64: string
44 /** The recorder's native mime type, e.g. `audio/webm;codecs=opus`. */
45 mimeType: string
46 /** Recording length in milliseconds. */
47 durationMs: number
48 /**
49 * Ready-to-use audio content part for `sendMessage`/generation prompts:
50 * `{ type: 'audio', source: { type: 'data', value: base64, mimeType } }`.
51 */
52 part: AudioPart
54​
55/**
56 * Framework-agnostic browser audio recorder. Wraps `getUserMedia` +
57 * `MediaRecorder`, returns the recorder's native output (no transcode), and
58 * builds a plug-and-play {@link AudioRecording.part}.
59 */
60export class AudioRecorder {
61 private readonly options: AudioRecorderOptions
62 private recorder: MediaRecorder | null = null
63 private stream: MediaStream | null = null
64 private chunks: Array<Blob> = []
65 private startedAt = 0
66 private _state: AudioRecorderState = 'idle'
67 private readonly listeners = new Set<(state: AudioRecorderState) => void>()
68 // True while start() is awaiting getUserMedia (state is still 'idle' then).
69 private starting = false
70 // Set by cancel()/teardown during that window so start() releases the
71 // freshly acquired stream instead of beginning a leaked recording.
72 private pendingCancel = false
73 private stopResolve: ((recording: AudioRecording) => void) | null = null
74 private stopReject: ((error: Error) => void) | null = null
75​
76 constructor(options: AudioRecorderOptions = {}) {
77 this.options = options
78 }
79​
80 /** Feature-detect the browser media APIs. SSR/Worker-safe. */
81 static isSupported(): boolean {
82 return (
83 typeof navigator !== 'undefined' &&
84 typeof navigator.mediaDevices !== 'undefined' &&
85 typeof navigator.mediaDevices.getUserMedia === 'function' &&
86 typeof MediaRecorder !== 'undefined'
87 )
88 }
89​
90 get state(): AudioRecorderState {
91 return this._state
92 }
93​
94 subscribe(cb: (state: AudioRecorderState) => void): () => void {
95 this.listeners.add(cb)
96 return () => this.listeners.delete(cb)
97 }
98​
99 /** Current recorder lifecycle state. */
100 getSnapshot = (): AudioRecorderState => this._state
101​
102 private setState(state: AudioRecorderState): void {
103 this._state = state
104 notifyListeners(this.listeners, state)
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 // Settle first. The pending stop() must not depend on listener code.
248 reject?.(new Error('Recording cancelled'))
249 this.setState('idle')
250 }
251​
252 private async finalize(): Promise<void> {
253 const mimeType = this.recorder?.mimeType || 'audio/webm'
254 const durationMs = Date.now() - this.startedAt
255 try {
256 const blob = new Blob(this.chunks, { type: mimeType })
257 const base64 = arrayBufferToBase64(await blob.arrayBuffer())
258 const recording: AudioRecording = {
259 blob,
260 base64,
261 mimeType,
262 durationMs,
263 part: {
264 type: 'audio',
265 source: { type: 'data', value: base64, mimeType },
266 },
267 }
268 this.releaseStream()
269 this.recorder = null
270 this.chunks = []
271 const resolve = this.stopResolve
272 this.stopResolve = null
273 this.stopReject = null
274 resolve?.(recording)
275 this.setState('idle')
276 } catch (err) {
277 this.handleError(
278 err instanceof Error ? err : new Error('Failed to finalize recording'),
279 )
280 }
281 }
282​
283 private handleError(error: Error): void {
284 this.releaseStream()
285 this.recorder = null
286 this.chunks = []
287 const reject = this.stopReject
288 this.stopResolve = null
289 this.stopReject = null
290 // Settle the pending stop() promise before listeners and the user callback
291 // run, so a throw there can't strand the awaiter (the two error channels
292 // are independent — see start()/stop() docs).
293 reject?.(error)
294 this.setState('idle')
295 this.notifyError(error)
296 }
297​
298 /** Invoke the user onError callback, isolating a throw so it can't disrupt
299 * internal state teardown or strand a pending promise. */
300 private notifyError(error: Error): void {
301 try {
302 this.options.onError?.(error)
303 } catch {
304 // A user onError that throws must not propagate into recorder internals.
305 }
306 }
307​
308 private releaseStream(): void {
309 this.stream?.getTracks().forEach((t) => t.stop())
310 this.stream = null
311 }
312​
313 /** Detach all event handlers so a stale recorder can't mutate our state. */
314 private detachRecorder(): void {
315 const recorder = this.recorder
316 if (!recorder) {
317 return
318 }
319 recorder.onstop = null
320 recorder.onerror = null
321 recorder.ondataavailable = null
322 }