wgpu-kit/media
Canvas recording, format negotiation, and Blob downloads.
Auxiliary inputs, dispatch counts, managed batches and typed kernels are released in 2.1.0. The original API retains the published npm 2.0.0 declarations and implementation as its historical audit baseline; Additions in 2.1.0 and 2.2.0 are identified on affected APIs and cite src files, without claiming a fresh audit of the entire API. Only actual public exports of this entry point are listed.
Source reference: 1 ↗
pickMimefunction
Select the first supported recording MIME type, without starting capture.
pickMime(): string | null;Parameters
This call takes no arguments.
Returns
string | null Supported MIME string; null if MediaRecorder is absent or none of the candidates is supported.
Behavior & constraints
- Actual 2.0.0 order: video/webm;codecs=vp9 → video/webm;codecs=vp8 → video/webm → video/mp4;codecs=avc1.42E01E → video/mp4. The declaration comment suggesting MP4 first is stale.
- isTypeSupported is capability negotiation, not a guarantee that a recording will produce bytes.
Examples
import { pickMime } from 'wgpu-kit/media';
console.log(pickMime() ?? 'Recording unavailable');CanvasRecorderclass
Records a canvas video stream through the browser MediaRecorder API.
class CanvasRecorderconstructorconstructor
Negotiate and retain the preferred MIME type.
new CanvasRecorder();Parameters
This call takes no arguments.
Returns
CanvasRecorder An idle recorder; capture has not started.
Errors & failure cases
- Throws Error('MediaRecorder is not supported in this environment') when pickMime() returns null.
mimeTypegetter
Chosen MIME type, fixed at construction.
get mimeType(): string;Returns
string Selected codec/container string.
recordinggetter
Whether the underlying recorder is currently in state recording.
get recording(): boolean;Returns
boolean False before start and after stop; true while recording.
startmethod
Begin capturing a canvas at a requested 60 frames per second.
start(canvas: HTMLCanvasElement, videoBitsPerSecond?: number): void;Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
canvas | HTMLCanvasElement | Yes | — | Canvas to record; its changing pixels become the video. No audio track is added. |
videoBitsPerSecond | number | No | 12_000_000 | Requested video bitrate in bits/second; the browser may choose the actual bitrate. |
Returns
void No return value.
Behavior & constraints
- Uses canvas.captureStream(60), MediaRecorder.start(250), and collects nonempty data chunks. It does not advance or redraw the canvas.
- Wait for the previous stop() promise before starting again. The recorder reference remains set until the stop event.
Errors & failure cases
- Throws Error('Recording already in progress') if an internal recorder exists. Browser captureStream/MediaRecorder errors also propagate, including an origin-tainted canvas or unsupported encoder.
stopmethod
Stop recording and join collected video chunks into a Blob.
stop(): Promise<RecordingResult>;Parameters
This call takes no arguments.
Returns
Promise<RecordingResult> Resolves after the MediaRecorder stop event with the recording data and elapsed wall-clock duration.
Behavior & constraints
- No MediaRecorder error listener, cancellation, or explicit stream-track cleanup is exposed. Call stop once per started session and handle rejection.
Errors & failure cases
- Rejects Error('没有进行中的录制') if no recorder is recording, and rejects if the final Blob has zero bytes. Native stop errors may reject too.
Examples
import { CanvasRecorder, downloadBlob } from 'wgpu-kit/media';
const recorder = new CanvasRecorder();
const canvas = document.querySelector<HTMLCanvasElement>('#canvas')!;
// Invoke start from a user action; keep rendering your canvas.
recorder.start(canvas, 8_000_000);
// Invoke this from a later Stop action.
async function finishRecording() {
const result = await recorder.stop();
const extension = result.mimeType.startsWith('video/mp4') ? 'mp4' : 'webm';
downloadBlob(result.blob, `capture.${extension}`);
}RecordingResultinterface
Metadata and bytes returned by CanvasRecorder.stop().
interface RecordingResult {
blob: Blob;
mimeType: string;
seconds: number;
bytes: number;
}Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
blob | Blob | Yes | — | Recorded video chunks combined into one Blob. |
mimeType | string | Yes | — | MIME selected by the recorder. |
seconds | number | Yes | — | Elapsed performance.now() time from start to stop event, in seconds; not measured media timeline duration. |
bytes | number | Yes | — | Blob.size in bytes. |
downloadBlobfunction
Ask the browser to download a Blob using an object URL.
downloadBlob(blob: Blob, filename: string): void;Parameters
| Name | Type | Required | Default | Meaning |
|---|---|---|---|---|
blob | Blob | Yes | — | Data to download. |
filename | string | Yes | — | Suggested download filename; browser policies may alter it. |
Returns
void No return value.
Behavior & constraints
- Requires a browser document. Creates and clicks an anchor, then revokes the object URL after 5000 ms. This is a download request, not a completion receipt.
Examples
import { downloadBlob } from 'wgpu-kit/media';
downloadBlob(new Blob(['hello'], { type: 'text/plain' }), 'hello.txt');画布录制、格式协商和 Blob 下载。
辅助输入、dispatch count、托管批次与类型化内核已随 2.1.0 发布。原 API 仍以 npm 2.0.0 声明与实现为历史核对基线;2.1.0 和 2.2.0 新增能力在对应 API 中注明并引用 src 文件,不代表整份 API 重新审计。只列出此入口实际导出的公开 API。
源码参考: 1 ↗
pickMimefunction
选取首个受支持的录制 MIME 类型,不会启动捕获。
pickMime(): string | null;参数
此调用不接收参数。
返回值
string | null 返回支持的 MIME 字符串;若不存在 MediaRecorder 或候选格式都不支持则返回 null。
行为与约束
- 2.0.0 实际顺序:video/webm;codecs=vp9 → video/webm;codecs=vp8 → video/webm → video/mp4;codecs=avc1.42E01E → video/mp4。声明中 MP4 优先的注释已过时。
- isTypeSupported 只是能力协商,并不保证录制一定能产出数据。
示例
import { pickMime } from 'wgpu-kit/media';
console.log(pickMime() ?? 'Recording unavailable');CanvasRecorderclass
通过浏览器 MediaRecorder API 录制画布视频流。
class CanvasRecorderconstructorconstructor
协商并保存首选 MIME 格式。
new CanvasRecorder();参数
此调用不接收参数。
返回值
CanvasRecorder 空闲录制器,尚未开始捕获。
错误与失败情况
- pickMime() 返回 null 时抛出 Error('MediaRecorder is not supported in this environment')。
mimeTypegetter
构造时选定的 MIME 类型。
get mimeType(): string;返回值
string 选中的编码器/容器字符串。
recordinggetter
底层录制器当前状态是否为 recording。
get recording(): boolean;返回值
boolean 启动前和停止后为 false,录制中为 true。
startmethod
以请求的 60 帧/秒开始捕获画布。
start(canvas: HTMLCanvasElement, videoBitsPerSecond?: number): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
canvas | HTMLCanvasElement | 是 | — | 待录制的画布;其像素变化构成视频,不添加音轨。 |
videoBitsPerSecond | number | 否 | 12_000_000 | 请求的视频比特率,单位比特/秒;实际码率由浏览器决定。 |
返回值
void 无返回值。
行为与约束
- 调用 canvas.captureStream(60)、MediaRecorder.start(250),收集非空数据块;不会推进模拟或重绘画布。
- 再次开始前等待上次 stop() Promise 完成;stop 事件之前内部仍保留录制器引用。
错误与失败情况
- 已有内部录制器时抛出 Error('Recording already in progress');浏览器 captureStream/MediaRecorder 错误也会直接传播,例如画布被跨域内容污染或编码器不可用。
stopmethod
结束录制,并将收集的视频块合并为 Blob。
stop(): Promise<RecordingResult>;参数
此调用不接收参数。
返回值
Promise<RecordingResult> MediaRecorder stop 事件后返回录制数据和经过的墙钟时间。
行为与约束
- 没有暴露 MediaRecorder 错误监听器、取消或显式视频轨道清理功能。每次启动后只调用一次 stop,并处理拒绝。
错误与失败情况
- 没有正在录制的实例时拒绝并返回 Error('没有进行中的录制');最终 Blob 为 0 字节时也拒绝。原生 stop 错误也可能导致拒绝。
示例
import { CanvasRecorder, downloadBlob } from 'wgpu-kit/media';
const recorder = new CanvasRecorder();
const canvas = document.querySelector<HTMLCanvasElement>('#canvas')!;
// Invoke start from a user action; keep rendering your canvas.
recorder.start(canvas, 8_000_000);
// Invoke this from a later Stop action.
async function finishRecording() {
const result = await recorder.stop();
const extension = result.mimeType.startsWith('video/mp4') ? 'mp4' : 'webm';
downloadBlob(result.blob, `capture.${extension}`);
}RecordingResultinterface
CanvasRecorder.stop() 返回的数据和元信息。
interface RecordingResult {
blob: Blob;
mimeType: string;
seconds: number;
bytes: number;
}参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
blob | Blob | 是 | — | 合并后的视频 Blob。 |
mimeType | string | 是 | — | 录制器选中的 MIME。 |
seconds | number | 是 | — | 从 start 到 stop 事件的 performance.now() 时间差,单位秒;不是解析媒体轨道得出的时长。 |
bytes | number | 是 | — | Blob.size,单位字节。 |
downloadBlobfunction
使用对象 URL 请求浏览器下载 Blob。
downloadBlob(blob: Blob, filename: string): void;参数
| 名称 | 类型 | 必填 | 默认值 | 含义 |
|---|---|---|---|---|
blob | Blob | 是 | — | 待下载的数据。 |
filename | string | 是 | — | 建议下载文件名,浏览器策略可能修改它。 |
返回值
void 无返回值。
行为与约束
- 需要浏览器 document;创建并点击链接,5000 ms 后释放对象 URL。此操作只是发起下载,不代表下载已完成。
示例
import { downloadBlob } from 'wgpu-kit/media';
downloadBlob(new Blob(['hello'], { type: 'text/plain' }), 'hello.txt');