fn

useUserMedia

v0.0.14testeddemo

Reactive navigator.mediaDevices.getUserMedia streaming. Acquires a MediaStream for camera/microphone capture, keeps it in sync with reactive constraints, and auto-restarts on constraint changes while enabled. SSR-safe and race-safe — overlapping acquisitions never leave an orphaned stream open.

Examples

ts
const { stream, enabled } = useUserMedia({ constraints: { video: true } });
enabled.value = true; // start capturing
ts
// Switch cameras reactively — the stream restarts automatically
const { constraints, start } = useUserMedia();
await start();
constraints.value = { video: { deviceId: nextCameraId } };

Demo

Loading demo…

Signature

ts
export function useUserMedia(options: UseUserMediaOptions ={ ... }

Parameters

ParameterTypeDescription
options?UseUserMediaOptionsOptions

Returns

UseUserMediaReturnReactive support flag, stream, controls, and reactive enabled/autoSwitch/constraints
PropertyTypeDescription
isSupportedReadonly<Ref<boolean>>Whether navigator.mediaDevices.getUserMedia is available.
streamReadonly<ShallowRef<MediaStream | undefined>>The active MediaStream, or undefined while stopped.
start() => Promise<MediaStream | undefined>Request the stream and mark it as enabled. Resolves with the resulting stream, or undefined when unsupported or already running.
stop() => voidStop all tracks, release the stream, and mark it as disabled.
restart() => Promise<MediaStream | undefined>Stop the current stream and acquire a fresh one with the latest constraints.
constraintsRef<MediaStreamConstraints | undefined>The constraints applied to the next acquisition. Mutating or replacing this re-acquires the stream while enabled and autoSwitch is true.
enabledShallowRef<boolean>Whether the stream is currently enabled. Toggle to start/stop.
autoSwitchShallowRef<boolean>Whether constraint changes auto-restart the stream while enabled.