Real-Time & Streaming From Zero · Episode 02
Getting Media: Camera, Mic, Screen
Getting Media: Camera, Mic, Screen is Episode 02 of Real-Time & Streaming From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
With a single permission prompt, the browser running this page can see through your
camera, listen on your microphone, and watch your entire screen — and hand all three to
fifty lines of JavaScript as live, frame-by-frame MediaStream objects. No
plugin, no install, no native app. The same three APIs power every video call, every
"share your screen," and every in-browser studio you've ever used. Today you learn all
three from zero.
The demo below boots into a synthetic source — an animated canvas
with a live clock — so it's alive the instant the page paints, with no permission and on
any origin (even file://). Then it offers three real upgrades: flip to your
camera, share your screen, or switch to your
mic and watch a real volume meter jump as you talk. Pick a device, apply
a resolution, switch sources live — and we'll stop every track cleanly so the camera light
actually goes off when you're done.
What you're looking at
Everything in that frame is a MediaStream being painted to a single
<canvas>. On first paint the stream comes from
makeSyntheticSource() — a canvas we animate ourselves and then turn
into a real stream with canvas.captureStream(30). That's the trick
that keeps the whole series alive without a camera: a fake source that is, as far as the
rest of the code is concerned, indistinguishable from a real one.
The buttons are the upgrades. "use camera" calls
getUserMedia({ video: true }); "share screen" calls
getDisplayMedia(); the mic stage adds { audio: true } and routes
the audio track into a Web Audio AnalyserNode to drive the green level meter.
Each one is gated behind your click and wrapped in try/catch — deny the
prompt, run on file://, or have no camera at all, and the demo simply prints a
status line and stays on the synthetic source. It never throws and never goes
dark.
Stage 1 — Synthetic preview (no permission)
The baseline. A canvas full of drifting colored blobs and a ticking clock, captured
into a MediaStream. This proves a subtle and useful fact:
a MediaStream doesn't have to come from hardware. A canvas, a
<video> element, even another peer connection can all produce one. Every
later stage swaps this stream out for a real one, but the rendering path — draw the current
source's video frame to our display canvas, 60 times a second — never changes.
Stage 2 — Camera
Click use camera. The browser shows its permission prompt (once per
origin), and on approval getUserMedia resolves to a stream carrying one live
video track. We point a hidden <video> element at it
(video.srcObject = stream) and copy its frames onto our canvas. The
<video> is muted and playsinline so it
autoplays on every browser including iOS.
// (a) getUserMedia with constraints + graceful fallback
async function useCamera(constraints = { video: true, audio: false }) {
if (!window.isSecureContext || !navigator.mediaDevices?.getUserMedia) {
setStatus('getUserMedia needs https or localhost — staying synthetic');
return null; // file:// lands here
}
try {
return await navigator.mediaDevices.getUserMedia(constraints);
} catch (e) {
// NotAllowedError (denied), NotFoundError (no cam), NotReadableError (in use)…
setStatus('camera unavailable — staying synthetic (' + e.name + ')');
return null; // NEVER throw — fall back
}
}
Notice the two guards. First we check isSecureContext and that
mediaDevices.getUserMedia even exists — on file:// it doesn't, so
we bail to synthetic before touching the API. Then the real call is wrapped so any
rejection (the user clicks "Block", there's no webcam, another app holds the camera)
becomes a quiet status line and a null return that our caller treats as "keep
the synthetic source."
Stage 3 — Mic + a live level meter
Audio has no pixels, so a silent mic looks identical to a dead one — which is exactly
why a level meter is the canonical "is my mic working?" UI. We request
{ audio: true }, take the stream's audio track, and feed it through the Web
Audio graph: MediaStreamSource → AnalyserNode. Each frame we read the
analyser's time-domain data, compute an RMS volume, and draw a bar. Talk, and it leaps.
// (c) a live mic level meter — Web Audio AnalyserNode on the stream's audio track
function makeMeter(stream) {
const Ctx = window.AudioContext || window.webkitAudioContext;
const ac = new Ctx();
ac.resume(); // gesture-gated; we're inside a click
const src = ac.createMediaStreamSource(stream);
const analyser = ac.createAnalyser();
analyser.fftSize = 1024;
src.connect(analyser); // NOTE: do NOT connect to ac.destination —
const buf = new Uint8Array(analyser.fftSize); // that routes the mic to the speakers = feedback
return function level() { // call once per frame → 0..1
analyser.getByteTimeDomainData(buf);
let sum = 0;
for (let i = 0; i < buf.length; i++) {
const v = (buf[i] - 128) / 128; // center the 0..255 byte around 0
sum += v * v;
}
return Math.sqrt(sum / buf.length); // RMS
};
}
Two things matter here. The AudioContext needs a user gesture to start, so
we only build the meter from inside the button handler and call resume(). And
we connect the source to the analyser only — never to ac.destination.
Routing the mic to the output loops your speakers straight back into your mic and produces
that howling feedback everyone has suffered on a bad call. The meter only needs to
measure the audio, not play it.
Stage 4 — Screen share
Click share screen. This is a different API — getDisplayMedia
— and the browser, not your code, draws the picker that lets the user choose a screen,
window, or tab. Your page never sees anything until the user explicitly picks a surface,
which is why screen capture can't be requested silently or remembered like a camera grant:
it always requires a fresh gesture and a fresh choice.
// (b) getDisplayMedia for screen share — picker is drawn by the browser
async function useScreen() {
if (!navigator.mediaDevices?.getDisplayMedia) {
setStatus('screen share unsupported here — staying synthetic');
return null;
}
try {
const stream = await navigator.mediaDevices.getDisplayMedia({
video: { frameRate: 30 },
audio: false, // tab/system audio where supported
});
// the user can also stop sharing from the browser's own bar:
stream.getVideoTracks()[0].onended = () => goSynthetic();
return stream;
} catch (e) {
setStatus('screen share cancelled — staying synthetic'); // user hit "Cancel"
return null;
}
}
Cancelling the picker rejects the promise with NotAllowedError — the same
error as a denied camera — so the same fallback applies: status line, stay synthetic. And
because the browser shows a persistent "you're sharing" bar with its own Stop button, we
listen for the track's onended event and flip back to synthetic when the user
stops sharing from outside our UI. A track can end without us asking; good code listens for
it.
Stage 5 — Constraints + devices
So far we've taken whatever camera and resolution the browser felt like giving us.
Constraints let us ask for specifics, and enumerateDevices
lets us see what's available. Pick a camera in the device dropdown or a resolution
in quality, and we re-request the stream with those constraints applied.
// (d) enumerate devices, switch camera + resolution, stop the old tracks
async function listCameras() {
const devices = await navigator.mediaDevices.enumerateDevices();
// labels are EMPTY until the user has granted camera/mic permission once
return devices.filter(d => d.kind === 'videoinput');
}
async function switchTo(deviceId, width, height) {
stopStream(current); // ← stop old tracks FIRST (see below)
const video = { width: { ideal: width }, height: { ideal: height } };
if (deviceId) video.deviceId = { exact: deviceId }; // pin to one camera
current = await useCamera({ video, audio: false });
if (current) {
const s = current.getVideoTracks()[0].getSettings();
setStatus(`live · ${s.width}×${s.height} @ ${Math.round(s.frameRate)}fps`);
}
}
function stopStream(stream) { // the most-forgotten line in WebRTC
stream?.getTracks().forEach(t => t.stop()); // turns the camera light OFF
}
Three things to internalize. Constraints like width: { ideal: 1280 } are
requests, not commands — the browser picks the closest mode the hardware actually
supports, which is why we read back the truth with getSettings() rather than
trusting what we asked for. Device labels ("FaceTime HD Camera") are blank until
the user has granted permission at least once, a privacy measure to stop pages
fingerprinting your hardware before you've opted in. And switching cameras means stopping
the old stream's tracks before opening the new one — otherwise the first camera
stays lit.
Stage 6 — The switcher
The payoff: flip between synthetic, camera, and screen live, with clean teardown every time. This is the heart of any source picker in a real video app, and the whole discipline fits in one rule — stop the tracks you're leaving before you start the ones you're going to.
// the switcher: one entry point, always tears down the previous source
let current = null; // the live MediaStream (or null = synthetic)
async function setSource(kind) {
stopStream(current); current = null; // 1. tear down old tracks
closeMeter(); // 2. close any AudioContext
if (kind === 'camera') current = await useCamera();
else if (kind === 'screen') current = await useScreen();
else if (kind === 'mic') current = await useCamera({ audio: true, video: false });
if (current) {
video.srcObject = current; // 3a. real source → preview
if (kind === 'mic') meter = makeMeter(current);
} else {
video.srcObject = synthetic.stream; // 3b. fell back → synthetic, no error
}
}
Because useCamera and useScreen return null
instead of throwing, the switcher's fallback is a plain else branch: if the
real source didn't materialize, point the preview at the synthetic stream and carry on. The
demo is always showing something live, and the camera light is always off the
moment you switch away.
The permission & secure-context model
These three APIs share a security model worth committing to memory, because it explains almost every "why doesn't my camera work" bug:
| Requirement | What it means | If violated |
|---|---|---|
| Secure context | https:// or localhost only | API is undefined on file:// / plain http |
| User gesture | Must be called from a click/tap handler | Prompt is suppressed or rejected |
| Explicit grant | User clicks "Allow" in the browser prompt | NotAllowedError |
| Hardware present | A camera/mic actually exists & is free | NotFoundError / NotReadableError |
Camera and mic grants are remembered per origin once given; screen share is
not — every getDisplayMedia call shows the picker again, by design. And until
a camera or mic grant exists, enumerateDevices hides device labels. That's why
the standard flow is: request once, then enumerate to populate your nice device
dropdown.
Common pitfalls
- Insecure context.
navigator.mediaDevicesisundefinedonfile://and plainhttp://. Opening this HTML by double-clicking it will only ever show the synthetic source — serve it overlocalhostorhttpsto unlock the camera. (That's the whole reason the synthetic path exists: the demo still works either way.) - The camera light stays on. Releasing the stream variable does
not release the hardware. You must call
track.stop()on every track. Forget it and the OS camera indicator stays lit and the device stays locked from other apps — the single most common beginner bug in media code. - Empty device labels.
enumerateDevicesreturns devices with blanklabelstrings until the user has granted permission once. Don't build a device picker that assumes labels exist on first load — request, then re-enumerate. - Permission denial crashes the page. A denied prompt
rejects the promise (
NotAllowedError). If youawaitit withouttry/catch, your whole init throws. Always catch and fall back. - Mic → speakers feedback. Connecting a
MediaStreamSourcetoaudioContext.destinationpipes your mic into your speakers and howls. To visualize audio, connect to anAnalyserNodeonly and stop there. - Video won't autoplay. A
<video>with a camera stream won't start unless it'smuted(andplaysinlineon iOS). We set both.
Exercises
- Torch & zoom. Some phone cameras expose
torchandzoomintrack.getCapabilities(). After starting the camera, calltrack.applyConstraints({ advanced: [{ torch: true }] })and add a zoom slider bound to the capability'smin/max. Feature-detect first — most desktops report neither, so gate the UI on whatgetCapabilities()returns. - Front/back camera. Instead of pinning a
deviceId, request{ video: { facingMode: 'environment' } }for the rear camera and'user'for the selfie cam, and add a flip button that re-requests with the other value (stopping the old track first). This is how mobile web apps switch cameras without enumerating. - Live settings readout. Add an overlay that calls
track.getSettings()every second and prints the realwidth×height,frameRate, anddeviceId. Apply a 1080p constraint on a 720p webcam and watch the numbers reveal what you actually got versus what you asked for.
What's next
Episode 03 — WebRTC: connect two peers with no server. Now that you can
capture a MediaStream, we'll send it across a real peer connection — two
RTCPeerConnections doing a genuine offer/answer/ICE handshake right inside this
one page, no signaling server and no second person required. The synthetic source you built
today becomes the video that flows down the wire.