Created
July 15, 2020 17:27
-
-
Save aneeshdurg/6c848b2eac5a21e7bf9e7db4046a6702 to your computer and use it in GitHub Desktop.
Using MediaSource with a ReadableStream (fetchAPI)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
/** | |
An example of using MediaSource with a stream. | |
Based off of http://nickdesaulniers.github.io/netfix/demo/bufferAll.html | |
*/ | |
document.addEventListener("DOMContentLoaded", async () => { | |
var video = document.querySelector('video'); | |
var assetURL = 'frag_bunny.mp4'; | |
// Need to be specific for Blink regarding codecs | |
// ./mp4info frag_bunny.mp4 | grep Codec | |
var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; | |
if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { | |
var mediaSource = new MediaSource(); | |
video.src = URL.createObjectURL(mediaSource); | |
mediaSource.addEventListener('sourceopen', sourceOpen); | |
} else { | |
console.error('Unsupported MIME type or codec: ', mimeCodec); | |
} | |
async function sourceOpen (_) { | |
var mediaSource = this; | |
var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); | |
const resp = await fetch(assetURL) | |
if (resp.status != 200) | |
throw new Error("Resp had status " + resp.status); | |
const reader = resp.body.getReader(); | |
// appendToBuffer reads the next chunk into memory and passes it to the | |
// sourceBuffer. We can't just pass in all the chunks at once because of | |
// the fact that SourceBuffer.appendBuffer seems to do some async | |
// processing under the hood. | |
async function appendToBuffer() { | |
const read = await reader.read(); | |
if (read.done) { | |
mediaSource.endOfStream(); | |
return; | |
} | |
console.log(read); | |
sourceBuffer.appendBuffer(read.value.buffer); | |
} | |
sourceBuffer.addEventListener('updateend', function (_) { | |
video.setAttribute("controls", "controls"); | |
appendToBuffer(); | |
}); | |
// Kick off initial loading | |
appendToBuffer(); | |
} | |
}); | |
</script> | |
<video></video> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment