Stream video using the MediaSource API
Stay organized with collections
Save and categorize content based on your preferences.
The MediaSource API extends the HTMLMediaElement to allow JavaScript to generate media streams for playback. Allowing JavaScript to generate streams facilitates a variety of use cases like adaptive streaming and time shifting live streams.
Here is a quick demo and example usage of API:
constNUM_CHUNKS=5;
varvideo=document.querySelector('video');
video.src=video.webkitMediaSourceURL;
video.addEventListener('webkitsourceopen',function(e){
varchunkSize=Math.ceil(file.size/NUM_CHUNKS);
// Slice the video into NUM_CHUNKS and append each to the media element.
for(vari=0;i < NUM_CHUNKS;++i){
varstartByte=chunkSize*i;
// file is a video file.
varchunk=file.slice(startByte,startByte+chunkSize);
varreader=newFileReader();
reader.onload=(function(idx){
returnfunction(e){
video.webkitSourceAppend(newUint8Array(e.target.result));
logger.log('appending chunk:'+idx);
if(idx==NUM_CHUNKS-1){
video.webkitSourceEndOfStream(HTMLMediaElement.EOS_NO_ERROR);
}
};
})(i);
reader.readAsArrayBuffer(chunk);
}
},false);
The example splits a .webm video into 5 chunks using the File APIs. The entire movie is then 'streamed' to a <video> tag by appending each chunk to the element using the MediaSource API.
If you're interested in learning more about the API, see the specification.
Support: Currently, the MediaSource API is only available in Chrome Dev Channel 17+ with the --enable-media-source flag set or enabled via about:flags.