# Media capture — photos, a live camera and voice recordings

> voice memosVoice memos, voice notes and any app that records audio, and any app where the person adds a photo or uses the camera: a plant or receipt identifier, profile and avatar photos, a selfie booth, a scanner. The photo picker that offers Take Photo and the photo library (preview, paste, drag-and-drop, downscale, location stripped), a live camera viewfinder (front/back switch, permission asked on the tap, a picker when the camera is blocked), and a voice recorder (timer, level meter, play back before saving).

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

The photo picker and the stream helpers above are this skill's two halves. Reach for the lightest
one that does the job:

| The app needs | Use |
| --- | --- |
| a photo or a few (a plant to identify, a receipt, an avatar, a product shot) | `PhotoPicker`: one input, no `capture`, so the phone offers Take Photo and the library |
| the camera as its whole point (a document scanner, a quick photo booth) | the two-button picker: `capture` on the main button, the library on the second |
| a camera that stays open (a QR scanner, a booth with a countdown or an overlay, AR) | the live viewfinder below |
| a voice memo, an audio note, a spoken answer | the recorder below |
| an audio file someone already has | `<input type="file" accept="audio/*">` behind a `Button` |

## A live viewfinder

A viewfinder starts on a tap ("Start camera"), never on mount. The tap opens the stream with
`openStream`, the video plays inline, a flip button switches between the front and back cameras,
and the shot is the current frame drawn to a canvas. When the stream will not open, the picker
takes its place, so the person can still hand over a photo.

```jsx
import { Button, ErrorNote, Row, Stack } from "@vibes.diy/ui";
import { openStream, stopStream, streamHelp } from "./lib/media.js";

function Viewfinder({ onShot }) {
  const videoRef = React.useRef(null);
  const streamRef = React.useRef(null);
  const [facing, setFacing] = React.useState("environment"); // "user" is the selfie camera
  const [live, setLive] = React.useState(false);
  const [problem, setProblem] = React.useState("");
  // Each open gets a number; closing, unmounting or a newer tap moves it on, so a stream that
  // arrives for an older one is stopped instead of left running.
  const request = React.useRef(0);

  const stop = () => {
    request.current += 1;
    stopStream(streamRef.current);
    streamRef.current = null;
    setLive(false);
  };
  React.useEffect(() => {
    const hide = () => document.visibilityState === "hidden" && stop();
    document.addEventListener("visibilitychange", hide);
    window.addEventListener("pagehide", stop);
    return () => {
      document.removeEventListener("visibilitychange", hide);
      window.removeEventListener("pagehide", stop);
      stop();
    };
  }, []);

  // Called only from a tap: Start camera, Try again, or the flip button.
  async function start(next = facing) {
    const mine = ++request.current;
    stopStream(streamRef.current);
    streamRef.current = null;
    const res = await openStream({ video: { facingMode: next, width: { ideal: 1280 } }, audio: false });
    if (mine !== request.current || !videoRef.current) {
      if (res.ok) stopStream(res.stream); // closed, unmounted or tapped again while the prompt was up
      return;
    }
    if (!res.ok) {
      setProblem(streamHelp(res.reason, "camera"));
      return;
    }
    setProblem("");
    streamRef.current = res.stream;
    videoRef.current.srcObject = res.stream;
    setFacing(next);
    setLive(true);
  }

  function snap() {
    const v = videoRef.current;
    const canvas = document.createElement("canvas");
    canvas.width = v.videoWidth;
    canvas.height = v.videoHeight;
    canvas.getContext("2d").drawImage(v, 0, 0);
    canvas.toBlob((blob) => onShot(new File([blob], `shot-${Date.now()}.jpg`, { type: "image/jpeg" })), "image/jpeg", 0.9);
  }

  return (
    <Stack gap={3}>
      {/* playsInline + muted let iOS play the stream in the page instead of full screen. */}
      <video ref={videoRef} autoPlay playsInline muted
        className={`aspect-3/4 w-full rounded-md bg-muted object-cover ${facing === "user" ? "-scale-x-100" : ""}`} />
      {live ? (
        <Row gap={2} justify="center" align="center">
          <Button size="lg" onClick={snap}>Take photo</Button>
          <Button variant="quiet" onClick={() => start(facing === "user" ? "environment" : "user")}>Switch camera</Button>
          <Button variant="quiet" onClick={stop}>Close camera</Button>
        </Row>
      ) : (
        <Button size="lg" onClick={() => start()}>{problem ? "Try the camera again" : "Start camera"}</Button>
      )}
      {problem && (
        <>
          <ErrorNote>{problem}</ErrorNote>
          <PhotoPicker label="Choose a photo instead" onChange={(files) => files[0] && onShot(files[0])} />
        </>
      )}
    </Stack>
  );
}
```

The selfie preview is mirrored, like a mirror; the saved shot is not. A frame from the canvas
carries no EXIF, so it is safe to store; run it through `shrinkPhoto` when it should be smaller.

## A voice recorder

Recording runs on a tap: Record opens the microphone with `openMic()` and starts a
`MediaRecorder`; while it runs the screen shows a red recording dot, a running timer, a level
meter, Stop and Cancel. Stop leaves the recording in a review state with a player, Save and
Record again; Cancel throws it away. The tracks stop as soon as recording ends.

```js
// lib/recorder.js — plain module, no React.
import { openMic, stopStream } from "./media.js";

// Safari records MP4/AAC, Chrome and Firefox WebM/Opus: take the first one this browser supports.
const TYPES = ["audio/webm;codecs=opus", "audio/mp4;codecs=mp4a.40.2", "audio/mp4", "audio/webm"];
export const pickMimeType = () => TYPES.find((t) => window.MediaRecorder?.isTypeSupported(t)) ?? "";

// Call from the Record tap. Resolves { ok: true, stop, cancel, level } or { ok: false, reason }.
export async function startRecording() {
  // The meter's AudioContext is created in the same tap, so iOS lets it run.
  const ctx = new (window.AudioContext || window.webkitAudioContext)();
  const mic = await openMic();
  if (!mic.ok) {
    ctx.close();
    return mic;
  }
  const mimeType = pickMimeType();
  const recorder = new MediaRecorder(mic.stream, mimeType ? { mimeType } : undefined);
  const chunks = [];
  recorder.ondataavailable = (e) => e.data.size > 0 && chunks.push(e.data);
  recorder.start(250);

  const analyser = ctx.createAnalyser();
  analyser.fftSize = 512;
  ctx.createMediaStreamSource(mic.stream).connect(analyser);
  const samples = new Uint8Array(analyser.fftSize);
  const level = () => { // 0..1, read from a requestAnimationFrame loop
    analyser.getByteTimeDomainData(samples);
    return Math.min(1, Math.max(...samples.map((s) => Math.abs(s - 128))) / 64);
  };

  const release = () => {
    stopStream(mic.stream);
    ctx.close();
  };
  const stop = () =>
    new Promise((resolve) => {
      recorder.onstop = () => {
        release();
        const type = recorder.mimeType || mimeType || "audio/webm";
        const ext = type.includes("mp4") ? "m4a" : "webm";
        resolve(new File([new Blob(chunks, { type })], `memo-${Date.now()}.${ext}`, { type }));
      };
      recorder.stop();
    });
  const cancel = () => {
    recorder.onstop = release;
    recorder.stop();
  };
  return { ok: true, stop, cancel, level };
}
```

In the component, keep the session in a ref and cancel it in the unmount cleanup, on
`pagehide` and when `visibilitychange` finds the page hidden, the same as a stream, and number each Record tap like the viewfinder's `request` so a
session that starts after the person left is cancelled at once. While it records:

```jsx
<Row gap={3} align="center" aria-live="polite">
  <span className="h-3 w-3 animate-pulse rounded-full bg-destructive" aria-hidden="true" />
  <Text>Recording {Math.floor(secs / 60)}:{String(secs % 60).padStart(2, "0")}</Text>
  <Progress value={meter * 100} label="Input level" />
  <Button onClick={finish}>Stop</Button>
  <Button variant="quiet" onClick={() => session.current.cancel()}>Cancel</Button>
</Row>
```

`secs` counts from a `startedAt` timestamp and `meter` reads `level()`, both from one
`requestAnimationFrame` loop (`Progress` comes from `@vibes.diy/ui/interactive`). Play the take back
before saving it: `<audio controls src={URL.createObjectURL(file)} />`, the duration beside it,
then save the `File` as `_files: { audio: file }` on the memo's record, whose `url` plays it later
in the same `<audio controls>`. A memo app shows its list of saved recordings, newest first, each
with its own player.
