MediaAdvancedSSR-safehooks/media/useMicrophone.ts

useMicrophone

getUserMedia audio stream.

Import

TypeScript
import { useMicrophone } from '@/hooks';

API

Signature

useMicrophone(options?) → { stream, start, stop, error }

When to use

Use useMicrophone instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Client-only browser APIs.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useMicrophone
Editor
function Mic() {
  const { stream, start, stop, error } = useMicrophone({ enabled: false });
  return (
    <div>
      <p>{stream ? 'Listening' : 'Idle'}</p>
      <button onClick={() => void start()}>Start</button>
      <button onClick={stop}>Stop</button>
      {error && <p>{error.message}</p>}
    </div>
  );
}
Preview

Implementation source

Full library source for useMicrophone — copy into your project when you are not installing a package yet.

hooks/media/useMicrophone.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import { hasNavigator, isBrowser } from '../utility/isBrowser';

export interface UseMicrophoneOptions {
  enabled?: boolean;
  constraints?: MediaStreamConstraints['audio'];
}

/** Request a microphone stream and release tracks on cleanup. */
export function useMicrophone(options: UseMicrophoneOptions = {}) {
  const { enabled = false, constraints = true } = options;
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [loading, setLoading] = useState(false);
  const streamRef = useRef<MediaStream | null>(null);

  const stop = useCallback(() => {
    streamRef.current?.getTracks().forEach((t) => t.stop());
    streamRef.current = null;
    setStream(null);
  }, []);

  const start = useCallback(async () => {
    if (!isBrowser() || !hasNavigator() || !navigator.mediaDevices?.getUserMedia) {
      setError(new Error('Microphone API is not supported'));
      return null;
    }
    setLoading(true);
    setError(null);
    try {
      stop();
      const media = await navigator.mediaDevices.getUserMedia({
        audio: constraints,
        video: false,
      });
      streamRef.current = media;
      setStream(media);
      return media;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String(e));
      setError(err);
      return null;
    } finally {
      setLoading(false);
    }
  }, [constraints, stop]);

  useEffect(() => {
    if (enabled) void start();
    else stop();
    return stop;
  }, [enabled]);

  const supported =
    isBrowser() && hasNavigator() && !!navigator.mediaDevices?.getUserMedia;

  return { stream, error, loading, start, stop, supported };
}

Copy-paste example

useMicrophone.example.tsx
'use client';

import { useMicrophone } from '@/hooks';

export function Mic() {
  const { stream, start, stop, error } = useMicrophone({ enabled: false });
  return (
    <div>
      <p>{stream ? 'Listening' : 'Idle'}</p>
      <button onClick={() => void start()}>Start</button>
      <button onClick={stop}>Stop</button>
      {error && <p>{error.message}</p>}
    </div>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Always stop tracks on unmount (hooks clean up streams they own).
  • Source of truth: open hooks/media/useMicrophone.ts for implementation details