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

use-audio-recorder.ts

118 lines4.5 KB

1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { AudioRecorder } from '@tanstack/ai-client'
3import type {
4 AudioRecorderOptions,
5 AudioRecording,
6 InferAudioRecordingOutput,
7} from '@tanstack/ai-client'
8​
9export type UseAudioRecorderOptions<TOnComplete> = AudioRecorderOptions & {
10 /**
11 * Optional transform applied to the recording when `stop()` resolves. Its
12 * (awaited) return value becomes `recording` and the resolved value of
13 * `stop()`. Return nothing to keep the raw `AudioRecording`.
14 */
15 onComplete?: TOnComplete
17​
18export interface UseAudioRecorderReturn<TOutput> {
19 /** Latest recording (transformed if `onComplete` provided), or null. */
20 recording: TOutput | null
21 /** True while actively capturing audio. */
22 isRecording: boolean
23 /** Whether the browser supports recording (getUserMedia + MediaRecorder). */
24 isSupported: boolean
25 /** Acquire the mic and begin recording. */
26 start: () => Promise<void>
27 /** Stop and resolve with the completed recording (transformed if `onComplete` provided). */
28 stop: () => Promise<TOutput>
29 /** Discard the in-progress recording and release the mic. */
30 cancel: () => void
32​
33/**
34 * React hook for recording an audio message. The resolved
35 * {@link AudioRecording} carries `.part` (an audio content part for
36 * `useChat.sendMessage`) and `.base64` (for the generation hooks).
37 *
38 * Errors are delivered via `onError`. `start()` and `stop()` also reject on
39 * failure (and `stop()` rejects with `Recording cancelled` if the component
40 * unmounts while a stop is in flight) — handle one channel, not both.
41 *
42 * @example
43 * ```tsx
44 * const { isRecording, start, stop, recording } = useAudioRecorder()
45 * const { sendMessage } = useChat({ threadId: 'support-1', connection })
46 * // ...
47 * const rec = await stop()
48 * sendMessage({ content: [rec.part] })
49 * ```
50 */
51// The transforming overload requires `onComplete`. Without that constraint an
52// options object carrying only unrelated keys (`useAudioRecorder({ onError })`)
53// still matches it, `TOnComplete` infers as `unknown`, and `recording`/`stop()`
54// collapse to `unknown` — so passing any option would silently cost you the
55// `AudioRecording` type. Requiring it here sends those calls to the second
56// overload instead (issue #1001).
57export function useAudioRecorder<
58 TOnComplete extends (recording: AudioRecording) => unknown,
59>(
60 options: UseAudioRecorderOptions<TOnComplete> & { onComplete: TOnComplete },
61): UseAudioRecorderReturn<InferAudioRecordingOutput<TOnComplete>>
62export function useAudioRecorder(
63 options?: UseAudioRecorderOptions<undefined>,
64): UseAudioRecorderReturn<AudioRecording>
65export function useAudioRecorder(
66 options: UseAudioRecorderOptions<(recording: AudioRecording) => unknown> = {},
67): UseAudioRecorderReturn<unknown> {
68 const [isRecording, setIsRecording] = useState(false)
69 const [recording, setRecording] = useState<unknown>(null)
70 // Read the freshest callbacks at fire time without recreating the recorder.
71 const optionsRef = useRef(options)
72 optionsRef.current = options
73​
74 const recorder = useMemo(
75 () =>
76 new AudioRecorder({
77 ...(options.audio !== undefined && { audio: options.audio }),
78 ...(options.mimeType !== undefined && { mimeType: options.mimeType }),
79 onError: (err) => optionsRef.current.onError?.(err),
80 }),
81 // Recorder config (audio/mimeType) is captured once at mount, matching the
82 // other hooks' create-once pattern.
83 [],
84 )
85​
86 useEffect(() => {
87 const unsubscribe = recorder.subscribe((state) => {
88 setIsRecording(state === 'recording')
89 })
90 return () => {
91 unsubscribe()
92 recorder.cancel()
93 }
94 }, [recorder])
95​
96 const start = useCallback(() => recorder.start(), [recorder])
97 const stop = useCallback(async () => {
98 const recording = await recorder.stop()
99 const transformed = await optionsRef.current.onComplete?.(recording)
100 // Only `undefined` (returning nothing) falls back to the raw recording, so
101 // a transform that returns null is preserved — matching the inferred type,
102 // which excludes only undefined/void/null from the transform's return.
103 const output = transformed === undefined ? recording : transformed
104 setRecording(() => output)
105 return output
106 }, [recorder])
107 const cancel = useCallback(() => recorder.cancel(), [recorder])
108​
109 return {
110 recording,
111 isRecording,
112 // recording is client-only; if SSR'd, gate UI on a mounted flag.
113 isSupported: AudioRecorder.isSupported(),
114 start,
115 stop,
116 cancel,
117 }