# Microphone and camera streams — asked for on the tap, stopped when done

> Opening the microphone or camera: getUserMedia inside the tap that needs it, voice and music constraints, a plain reason when the stream is blocked, missing or busy, and every track stopped on finish, unmount and page hide.

Source: https://good.vibes.diy/docs/reference/mic-capture

`navigator.mediaDevices.getUserMedia` is a browser built-in. **Ask for the microphone or camera
inside the tap that needs it.** The person presses Record, Start camera or Tune, and that
handler's first `await` is the request, so the browser's permission prompt answers their own
press. A request on mount, in a `useEffect` or on page load asks a stranger for their microphone
before they know why, and on iOS it may never show at all.

## `lib/media.js` — open, explain, stop

```js
// lib/media.js — plain module, no React.
export const VOICE = { echoCancellation: true, noiseSuppression: true, autoGainControl: true };
export const MUSIC = { echoCancellation: false, noiseSuppression: false, autoGainControl: false };

// Call from the tap handler. Resolves { ok: true, stream } or { ok: false, reason }.
export async function openStream(constraints) {
  if (!navigator.mediaDevices?.getUserMedia) return { ok: false, reason: "unsupported" };
  try {
    return { ok: true, stream: await navigator.mediaDevices.getUserMedia(constraints) };
  } catch (err) {
    if (err.name === "NotAllowedError" || err.name === "SecurityError") return { ok: false, reason: "blocked" };
    if (err.name === "NotFoundError" || err.name === "OverconstrainedError") return { ok: false, reason: "missing" };
    return { ok: false, reason: "busy" }; // NotReadableError, AbortError: another app holds it
  }
}

export const openMic = (audio = VOICE) => openStream({ audio, video: false });

// Every track stops: the browser's recording light goes out and the device is free again.
export function stopStream(stream) {
  stream?.getTracks().forEach((t) => t.stop());
}

// What to say when the stream did not open, in the app's own words.
export function streamHelp(reason, device = "microphone") {
  if (reason === "blocked") return `Allow the ${device} for this site in your browser settings, then tap again.`;
  if (reason === "missing") return `Connect a ${device} and tap again.`;
  if (reason === "busy") return `Close the other app using your ${device}, then tap again.`;
  return `This browser keeps the ${device} to itself. The rest of the app still works.`;
}
```

## Stop the tracks when the person is done

Stop every track when recording ends, when the component unmounts and when the page is hidden
(another tab, the phone locked), so the recording indicator never stays lit behind the person's
back. Switching tabs or locking a phone hides the page without a `pagehide`, so listen for
`visibilitychange` as well:

```jsx
const streamRef = React.useRef(null);
React.useEffect(() => {
  const stop = () => {
    stopStream(streamRef.current);
    streamRef.current = null;
  };
  const hide = () => document.visibilityState === "hidden" && stop();
  document.addEventListener("visibilitychange", hide);
  window.addEventListener("pagehide", stop);
  return () => {
    document.removeEventListener("visibilitychange", hide);
    window.removeEventListener("pagehide", stop);
    stop();
  };
}, []);
```

A stopped stream comes back with the next tap, never on its own when the page shows again.

## A blocked state that keeps the app useful

When `openStream` resolves `ok: false`, show `streamHelp(reason)` beside the button that asked,
keep that button working so a second tap retries, and offer the path that needs no permission: a
typed note beside a voice memo, `<input type="file" accept="audio/*">` for a recording they already
have, or the photo picker beside a live camera.
