SourceBuffer
注意:此功能在 专用 Web Workers 中可用。
SourceBuffer 接口代表要通过 对象传递给 MediaSource 并播放的媒体块。这可以由一个或多个媒体片段组成。HTMLMediaElement
实例属性
SourceBuffer.appendWindowEnd-
控制追加窗口的结束时间戳。
SourceBuffer.appendWindowStart-
控制 追加窗口 的开始时间戳。这是一个时间戳范围,可用于过滤要追加到
SourceBuffer的媒体数据。时间戳在此范围内的编码媒体帧将被追加,而范围外的将被过滤掉。 SourceBuffer.audioTracks只读-
当前包含在
SourceBuffer中的音频轨列表。 SourceBuffer.buffered只读-
返回当前在
SourceBuffer中缓冲的时间范围。 SourceBuffer.mode-
控制
SourceBuffer中媒体片段的排序方式,即它们是否可以按任意顺序追加,还是必须保持严格的顺序。 SourceBuffer.textTracks只读 实验性-
当前包含在
SourceBuffer中的文本轨列表。 SourceBuffer.timestampOffset-
控制应用于后续追加到
SourceBuffer的媒体片段内的时间戳的偏移量。 SourceBuffer.updating只读-
一个布尔值,指示
SourceBuffer当前是否正在更新 — 即,是否正在进行SourceBuffer.appendBuffer()或SourceBuffer.remove()操作。 SourceBuffer.videoTracks只读-
当前包含在
SourceBuffer中的视频轨列表。
实例方法
继承其父接口 EventTarget 的方法。
SourceBuffer.abort()-
中止当前片段并重置片段解析器。
SourceBuffer.appendBuffer()-
将来自
ArrayBuffer、TypedArray或DataView对象的媒体片段数据追加到SourceBuffer。 SourceBuffer.appendBufferAsync()非标准 实验性-
开始异步将指定缓冲区追加到
SourceBuffer的过程。返回一个,该PromisePromise在缓冲区被追加后 fulfilled。 SourceBuffer.changeType()-
更改未来对
appendBuffer()的调用所期望的新数据遵循的 MIME 类型。 SourceBuffer.remove()-
从
SourceBuffer中删除特定时间范围内的媒体片段。 SourceBuffer.removeAsync()非标准 实验性-
开始异步从
SourceBuffer中删除指定范围内媒体片段的过程。返回一个,该PromisePromise在所有匹配的片段都被删除后 fulfilled。
事件
abort-
当缓冲区追加被中止时触发,因为在
SourceBuffer.appendBuffer()算法仍在运行时调用了SourceBuffer.abort()或MediaSource.removeSourceBuffer()方法。从SourceBuffer.updatingtrue变为false。 error-
当在处理
appendBuffer()操作时发生错误时触发。从SourceBuffer.updatingtrue变为false。 update-
每当
SourceBuffer.appendBuffer()或SourceBuffer.remove()完成时触发。从SourceBuffer.updatingtrue变为false。 updateend-
在
appendBuffer()或remove()操作(无论是否成功)完成之后触发。此事件在update、error或abort事件之后触发。 updatestart-
当
appendBuffer()或remove()操作开始时触发。从updatingfalse变为true。
示例
分块加载视频
以下示例以尽可能快的速度分块加载视频,并在能够播放时立即播放。
您可以在 https://github.com/mdn/dom-examples/tree/main/sourcebuffer 找到完整的代码,并在 https://mdn.github.io/dom-examples/sourcebuffer/ 现场试用演示。
const video = document.querySelector("video");
const assetURL = "frag_bunny.mp4";
// Need to be specific for Blink regarding codecs
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
function loadVideo() {
if (MediaSource.isTypeSupported(mimeCodec)) {
const mediaSource = new MediaSource();
console.log(mediaSource.readyState); // closed
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
console.error("Unsupported MIME type or codec: ", mimeCodec);
}
}
async function sourceOpen() {
console.log(this.readyState); // open
const sourceBuffer = this.addSourceBuffer(mimeCodec);
const response = await fetch(assetURL);
const buffer = await response.arrayBuffer();
sourceBuffer.addEventListener("updateend", () => {
this.endOfStream();
video.play();
console.log(this.readyState); // ended
});
sourceBuffer.appendBuffer(buffer);
}
const load = document.querySelector("#load");
load.addEventListener("click", loadVideo);
规范
| 规范 |
|---|
| Media Source Extensions™ # sourcebuffer |
浏览器兼容性
加载中…