Skip to content

Instantly share code, notes, and snippets.

@jerinisready
Created January 30, 2020 08:19
Show Gist options
  • Save jerinisready/959a68ce14f6f1ebacec5eb20e0e7994 to your computer and use it in GitHub Desktop.
Save jerinisready/959a68ce14f6f1ebacec5eb20e0e7994 to your computer and use it in GitHub Desktop.
this is how to load a video via buffering Credits : Google Developrs at Medium :https://medium.com/google-developers/use-video-loops-with-interactive-canvas-dc7503e95c6a
<!doctype html>
<head>
<title> Canvas Draw </title>
</head>
<body>
<video id="can_video"></video>
</body>
<script>
/**
* Use FFmpeg to convert the file to have the correct code:
``ffmpeg -i video.mp4 -an -codec:v libx264 -profile:v baseline -level 3 -b:v 2000k videocodec.mp4``
* Run the following command to put the header at the front of the file and to ensure that the fragments start with Random Access Points:
`` MP4Box -dash 1000 -rap -frag-rap videocodec.mp4 ``
* A new MP4 file is generated with a “_dashinit” postfix in the filename. Upload this file to your web server.
*/
(() => {
var allSegments;
var sourceBuffer;
function fileDownload(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.send();
xhr.onload = function(e) {
if (xhr.status != 200) {
onLoad();
return;
}
onLoad(xhr.response);
};
xhr.onerror = function(e) {
video.src = null;
};
};
function onLoad(arrayBuffer) {
if (!arrayBuffer) {
video.src = null;
return;
}
allSegments = new Uint8Array(arrayBuffer);
sourceBuffer.appendBuffer(allSegments);
processNextSegment();
}
function processNextSegment() {
// Wait for the source buffer to be updated
if (!sourceBuffer.updating &&
sourceBuffer.buffered.length > 0) {
// Only push a new fragment if we are not updating and we have
// less than 10 seconds in the pipeline
if (sourceBuffer.buffered.end(
sourceBuffer.buffered.length - 1) -
video.currentTime < 10) {
// Append the video segments and adjust the timestamp offset
// forward
sourceBuffer.timestampOffset =
sourceBuffer.buffered.end(
sourceBuffer.buffered.length - 1);
sourceBuffer.appendBuffer(allSegments);
}
// Start playing the video
if (video.paused) {
video.play();
}
}
repeat()
};
function repeat(){
setTimeout(processNextSegment, 1000);
}
let video = document.getElementById('can_video');
let mediaSource = new MediaSource();
video.src = window.URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', function(){
sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42c01e"');
fileDownload('videocodec_dashinit.mp4');
});
})()
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment