Dun*_*ick 5 javascript buffer stream fetch media-source
我正在fetch()从 API 获取视频。
这response.body是一个可读的流。所以我把它读进了reader.
然后将所有块 ( value) 推入块数组 ( chunks.push(value)) 中。
然后,块数组被转换为 arrayBuffer ( let buffer = await blob.arrayBuffer()),因为 blob 无法附加到 sourceBuffer。
以上所有步骤均正确运行!我唯一的问题是将缓冲区附加到 sourceBuffer ( sourceBuffer.appendBuffer(buffer)) 中。
控制台没有弹出错误,但 sourceBuffer 没有更新。它保持空着。
有人知道发生了什么事吗?
多谢
<body>
<video id="test-video-api">
</video>
<script>
const fetchUrl = "https://myserver/api/video?fuid=12345";
const videoTag = document.getElementById("test-video-api");
function getVideo(){
if (window.MediaSource) {
var mediaSource = new MediaSource();
videoTag.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen);
} else {
console.log("The Media Source Extensions API is not supported.")
}
async function sourceOpen(e) {
URL.revokeObjectURL(videoTag.src);
const mimeCodec = 'video/mp4; codecs="avc1.4d400d,mp4a.40.2"; profiles="isom,iso2,avc1,mp41"';
var mediaSource = e.target;
var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
let chunks = [];
let response = await fetch(fetchUrl, {method: "GET", credentials: "include"});
const reader = response.body.getReader();
while (true){
const {done, value} = await reader.read();
chunks.push(value);
if(done){
let blob = new Blob(chunks);
let buffer = await blob.arrayBuffer();
sourceBuffer.appendBuffer(buffer);
break
}
}
}
}
getVideo()
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
可能您需要等待缓冲区完成更新
还有 chunks.push(value); 如果(完成)之后
while (true) {
const {done, value} = await reader.read();
if (done) {
let blob = new Blob(chunks);
let buffer = await blob.arrayBuffer();
while (true) {
if (!sourceBuffer.updating) break
console.log('bufferupdating, so wait...')
await new Promise(resolve => setTimeout(resolve, 50));
}
sourceBuffer.appendBuffer(buffer);
while (true) {
if (!sourceBuffer.updating) break
console.log('buffer updating, so wait...')
await new Promise(resolve => setTimeout(resolve, 50));
}
break
}
chunks.push(value);
total += value.length;
console.log(total)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1862 次 |
| 最近记录: |