Skip to content

Instantly share code, notes, and snippets.

@jpmedley
Last active March 13, 2017 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpmedley/cfd76957b9d7ff6ec6f3070ef1dfb618 to your computer and use it in GitHub Desktop.
Save jpmedley/cfd76957b9d7ff6ec6f3070ef1dfb618 to your computer and use it in GitHub Desktop.
Inserted fragment.
<!DOCTYPE html>
<html>
<!-- Media streaming example "Segment Request Array Insertion."
Based on ss-array.html, this is an experiment for inserting an ancillary
buffer into a continuous buffer streeam.
-->
<head>
<meta charset="utf-8" />
<title>Segment Request Array Insertion</title>
<link href="styles.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
video {
max-width: 100%;
}
</style>
</head>
<body>
<h1>Segment Request Array Insertion</h1>
<video autoplay controls></video>
<script>
var vidElement = document.querySelector('video');
if (window.MediaSource) {
var mediaSource = new MediaSource();
vidElement.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen);
} else {
console.log("The Media Source Extensions API is not supported.")
}
function getSources() {
// This would probably be in a json or xml file from the server, but
// this serves the purpose for demo.
let sources = []
// Add the pieces of droid.webm to an array.
for (let i = 1; i < 9; i++) {
sources.push('media/droid00' + i.toString() + '.webm');
}
// Insert an extraneous *.webm file.
sources.splice(1, 0, 'media/pd.webm');
return sources;
}
function sourceOpen(e) {
let sources = getSources();
URL.revokeObjectURL(vidElement.src);
var mimeCodec = 'video/webm; codecs="opus, vp9"';
var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
sourceBuffer.mode = 'sequence';
var hasListener = false;
(function readChunk(chunk) {
if (!hasListener) {
sourceBuffer.addEventListener('updateend', e => {
if (!sourceBuffer.updating && mediaSource.readyState === 'open') {
if (sources.length) {
readChunk(sources.shift());
} else {
mediaSource.endOfStream();
}
}
});
hasListener = true;
}
fetch(chunk)
.then(response => {
return response.arrayBuffer();
})
.then(arrayBuffer => {
sourceBuffer.appendBuffer(arrayBuffer);
});
})(sources.shift());
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment