【问题标题】:Stream video and play ajaxly流式传输视频和 ajaxly 播放
【发布时间】: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


    【解决方案1】:

    根本原因是你的视频资源需要经过转换才能正常运行。如果您的 .mp4 是零散的,它会正常工作。

    您可以使用Bento4 fragmentment Tools 转换您的.mp4 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2011-09-25
      • 2015-05-06
      • 1970-01-01
      相关资源
      最近更新 更多