【发布时间】:2022-01-26 22:18:27
【问题描述】:
我有一个视频,我想使用 asp.net core web API 在 react 和 stream 中播放
我需要 Ajaxly 获取视频,因为我需要将访问令牌传递给服务器以获取视频。
所以在后端我尝试了这个:
[HttpGet]
public async Task<IActionResult> Stream()
{
var path = _env.ContentRootPath + $"\\Videos\\test.mp4";
var file = new FileInfo(path);
var length = file.Length;
Response.Headers.Add("Accept-Ranges", "bytes");
Response.Headers.Add("Content-Length", $"{length / 10}");
return PhysicalFile($"{path}", "application/octet-stream", enableRangeProcessing: true);
}
在前端我试过这个:
const VideGetter = () => {
const video = useRef(null);
useEffect(() => {
var assetURL = "https://localhost:4001/api/Stream";
var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) {
var mediaSource = new MediaSource();
video.current.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);
fetchAB(assetURL, function (buf) {
sourceBuffer.addEventListener("updateend", function (_) {
mediaSource.endOfStream();
video.play();
});
sourceBuffer.appendBuffer(buf);
});
}
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();
}
});
return (
<video controls loop muted>
<source
src=""
type="video/mp4"
/>
Your browser does not support the video tag. upgrade your browser.
</video>
);
};
但我有这个:
最后的 mediaSource 有这个值:
MediaSource
activeSourceBuffers: SourceBufferList {length: 0, onaddsourcebuffer: null, onremovesourcebuffer: null}
duration: NaN
onsourceclose: null
onsourceended: null
onsourceopen: null
readyState: "closed"
我错过了什么?
【问题讨论】:
标签: reactjs asp.net-core asp.net-web-api video-streaming