Reputation: 158
I have a video that I want to play in react and stream using asp.net core web API
I need to get the video Ajaxly because I need to pass an access token to the server to get the video.
so at the backend i tried this:
[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);
}
at the frontend i tried this:
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>
);
};
but i have got this:
and the mediaSource at the end has this value:
MediaSource
activeSourceBuffers: SourceBufferList {length: 0, onaddsourcebuffer: null, onremovesourcebuffer: null}
duration: NaN
onsourceclose: null
onsourceended: null
onsourceopen: null
readyState: "closed"
what i've missed?
Upvotes: 0
Views: 234
Reputation: 22029
The root cause is that your video resources need to be converted before they can run normally. If your .mp4 is fragmented and it will works fine.
You can convert your .mp4 file by using Bento4 fragmentment Tools
.
Upvotes: 1