const mediaSource = new MediaSource();
const video = document.querySelector("video");
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener("sourceopen", async () => {
const sourceBuffer = mediaSource.addSourceBuffer(
'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
);
const buffer = await fetch("/my-video-segment.mp4").then((res) =>
res.arrayBuffer(),
);
sourceBuffer.appendBuffer(buffer);
sourceBuffer.addEventListener("updateend", () => {
if (mediaSource.readyState === "open") {
mediaSource.endOfStream();
}
});
});SourceBuffer: appendBuffer() method / notebook
SourceBuffer: appendBuffer() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
sourceBuffer.addEventListener("error", (e) => {
console.error("Error appending buffer:", e);
// Handle the error appropriately, e.g., show a message to the user,
// try a different source, or stop playback.
});
try {
sourceBuffer.appendBuffer(data);
} catch (e) {
if (e.name === "InvalidStateError") {
console.error(
"InvalidStateError: The SourceBuffer is in an invalid state.",
);
} else if (e.name === "QuotaExceededError") {
console.error("QuotaExceededError: The buffer is full.");
} else {
console.error("An unexpected error occurred:", e);
}
}