I am trying to play a video using javascript mediasource to hide video URL from the users. But I get an error as,
Uncaught InvalidStateError: Failed to execute 'endOfStream' on 'MediaSource': The MediaSource's readyState is not 'open'. And it would also be helpful if the video type and codes to be passed dynamically.
Below is my code,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<video controls></video>
<script>
var video = document.querySelector('video');
var assetURL = 'adsss.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;
//console.log(mediaSource.readyState); // closed
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen);
} else {
console.error('Unsupported MIME type or codec: ', mimeCodec);
}
function sourceOpen (_) {
console.log(this.readyState); // open
var mediaSource = this;
console.log(mediaSource);
var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
console.log(sourceBuffer);
fetchAB(assetURL, function (buf) {
sourceBuffer.addEventListener('updateend', function (_) {
mediaSource.endOfStream();
video.play();
console.log(mediaSource.readyState); // ended
});
sourceBuffer.appendBuffer(buf);
});
};
function fetchAB (url, cb) {
console.log(url);
var xhr = new XMLHttpRequest;
xhr.open('get', url);
console.log(xhr);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
cb(xhr.response);
console.log(xhr.response);
};
xhr.send();
};
</script>
The reason why the above code was not working is that, only fragmented mp4 videos with moov(movie header box) moved at the beginning will be played using the Media source.
Refer the below links, 1) Unable to get MediaSource working with mp4 format in chrome 2) What exactly is Fragmented mp4(fMP4)? How is it different from normal mp4?
You can fragment your videos using MP4box tool with the following command,
MP4Box -dash 1000 -rap -frag-rap test.mp4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With