MediaRecorder API example
MediaRecorder API example. Record a MediaStream with a chosen codec, then download the Blob. A stream is not a file.
The problem
A live MediaStream is pixels in motion. Saving a video means encoding those frames into a container
the browser can play later.
The method
MediaRecorder is the high-level encoder. Hand it a stream, get a file.
VideoEncoder is the other path. You pull frames, you compress them, you get packets. There is no
file until something muxes those packets. This lab skips the muxer and unpacks the packets with
VideoDecoder onto a canvas.
What to do
- Run
isTypeSupported(). Pick a mime type. - Start the camera. Record with
MediaRecorder. - Capture a batch and encode it with each mime. Same frames, different codecs.
- Record with
VideoEncoderand watch the frame count.
MediaRecorder.isTypeSupported()
What this browser will encode. The selected type is what MediaRecorder gets.
MediaRecorder.isTypeSupported("video/webm;codecs=vp8")
MediaRecorder.isTypeSupported("video/mp4;codecs=avc1")
Pick a mime type.
MediaRecorder
Takes a MediaStream and writes a Blob. start(1000) emits a chunk every second. Pause,
resume, and requestData() work while it runs. Video only in this lab. Add an audio track and it
will mux that too.
const rec = new MediaRecorder(stream, { mimeType })
rec.ondataavailable = (e) => chunks.push(e.data)
rec.start(1000)
rec.stop()
const blob = new Blob(chunks, { type: rec.mimeType })
Same frames, every codec
Captures frames from the preview, then MediaRecorder encodes that same batch with any mime you
pick.
frames.push(await createImageBitmap(video))
const stream = canvas.captureStream(0)
const rec = new MediaRecorder(stream, { mimeType })
rec.start()
const track = stream.getVideoTracks()[0]
for (const frame of frames) {
ctx.drawImage(frame, 0, 0)
track.requestFrame()
await new Promise((resolve) => setTimeout(resolve, 1000 / 30))
}
rec.stop()
VideoEncoder
Yes
MediaRecorder hides this loop. Here you run it yourself. A cloned track keeps the preview alive.
Each VideoFrame is compressed into an EncodedVideoChunk. That is a packet, not a
movie. Stop to run the packets backwards through VideoDecoder.
- Clone the camera track.
MediaStreamTrackProcessorpulls oneVideoFrameat a time.encoder.encode(frame)compresses it.outputreceives a chunk.- Stop.
VideoDecoderdraws those chunks on a canvas. Still not a file.
const processor = new MediaStreamTrackProcessor({ track: track.clone() })
const encoder = new VideoEncoder({
output: (chunk) => chunks.push(chunk),
error,
})
encoder.configure({ codec: "vp8", width, height, bitrate: 2e6 })
const { value: frame } = await processor.readable.getReader().read()
encoder.encode(frame)
frame.close()