MSE的demo实现思路:首先准备fmp4格式的视频地址或者切片,接着将MSE挂载到video上,创建createObjectURL转二进制数据,fetch请求在线地址,分段请求,监听这个数据流的获取状态,当这个ReadyState为open的时候, sourceBuffer.appendBuffer(buf)处理接收到的数据,否则mediaSource.endOfStream()结束接收数据流。
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<video controls></video>
<script>
var video=document.querySelector('video');
// 视频 URL 队列(按顺序播放)
var assetURLs=[
....
];
// 当前播放的 URL 索引
var currentIndex=0;
// MIME 类型
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);
}
function sourceOpen (_) {
var mediaSource=this;
var sourceBuffer=mediaSource.addSourceBuffer(mimeCodec);
function loadNextVideo () {
if(currentIndex>=assetURLs.length) {
console.log('All videos played.');
return;
}
var assetURL=assetURLs[currentIndex];
fetchAB(assetURL,function(buf) {
sourceBuffer.addEventListener('updateend',function updateEndHandler (_) {
sourceBuffer.removeEventListener('updateend',updateEndHandler);
currentIndex++;
if(currentIndex<assetURLs.length) {
mediaSource.removeSourceBuffer(sourceBuffer); // 清空 SourceBuffer
mediaSource.endOfStream();
loadNextVideo(); // 加载下一个视频
} else {
mediaSource.endOfStream();
console.log('All videos loaded.');
}
video.play();
});
sourceBuffer.appendBuffer(buf);
});
}
loadNextVideo();
}
function fetchAB (url,cb) {
console.log(url);
var xhr=new XMLHttpRequest();
xhr.open('get',url);
xhr.responseType='arraybuffer';
xhr.onload=function() {
cb(xhr.response);
};
xhr.send();
}
</script>
</body>
</html>
标签:mediaSource,mimeCodec,案例,Range,video,currentIndex,var,MSE,sourceBuffer
From: https://blog.csdn.net/m0_72030584/article/details/144908452