【问题标题】:How to stream partially in react-native-video?如何在 react-native-video 中部分流式传输?
【发布时间】:2022-11-04 21:56:35
【问题描述】:

我正在使用节点后端来提供要流式传输的 mp4 视频。 此代码将视频作为一个块返回。

app.get('/video', (req, res) => {
    i++;
    const range = req.headers.range;
    if (!range) {
        res.status(400).send("Requires Range header");
    }
    else {
        console.log(`Range = ${range}`);
    }

    // get video stats
    const videoSize = fs.statSync(videoPath).size;

    // Parse Range
    // Example: "bytes=32324-"
    const CHUNK_SIZE = 10 ** 6;
    const start = Number(range.replace(/\D/g, ""));
    const end = Math.min(start + CHUNK_SIZE, videoSize - 1);

    // Create headers
    const contentLength = end - start + 1;
    console.log(`video hit (${i}). chunkSize=${CHUNK_SIZE}. start = ${start}. end = ${end}. contentLength = ${contentLength}, videoSize = ${videoSize}`);
    const headers = {
        "Content-Range": `bytes ${start}-${end}/${videoSize}`,
        "Accept-Ranges": "bytes",
        "Content-Length": contentLength,
        "Content-Type": "video/mp4",
    };

    // HTTP Status 206 for Partial Content
    res.writeHead(206, headers);

    // create video read stream for this particular chunk
    const videoStream = fs.createReadStream(videoPath, { start, end });
    // console.log(videoStream);

    // Stream the video chunk to the client
    videoStream.pipe(res);
});

我使用 react-native-video 来播放视频。

<Video
source={{
    uri: this.state.source.uri,
    type: 'mp4',
    headers: {
        'range': bytes=0-'
    }
}}

但是在播放完第一个块后它就停止了。如何加载下一个块? 我尝试将标头范围设置为大于 0 以尝试像这样加载下一个块。

headers: {
    'range': 'bytes=1000-'
}

后端被正确调用, 但它在前端给出了一个错误

{"error": {"extra": -2147483648, "what": 1}}

实际上,我在搜索如何流式传输视频时发现了将视频作为块返回的代码。但我不明白使用块的意义何在,因为 react-native-video 只能从直接 url 流式传输。谁能解释我应该只使用直接 url 还是继续使用块方法并寻找解决方案?

【问题讨论】:

    标签: node.js react-native


    【解决方案1】:

    我正在按照本教程设置 NodeJs Express 流 https://www.youtube.com/watch?v=VNQYwonNigw 。我认为这与您使用的资源相同。它对我来说很好。

    确保您的 videoPath 变量指向正确的资源(您没有在代码上定义 videoPath)。

    在 react-native 我有:

    <Video source={{
      uri: this.state.source.uri,
      type: 'mp4',
      headers: {
        'range': 'bytes=0-'
      }
    }}/>
    

    在您的代码中,您在字节 0 的开头缺少 '。

    我不需要在 react-native 上设置请求的范围。这似乎是由 react-native-video 自动处理的。当我在视频上按不同的时间时,它会正确加载。它还播放完整的视频,而不仅仅是第一个块。

    当 nodejs 服务器未运行时,我收到错误 error: {extra: -2147483648, what: 1}。启动它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      相关资源
      最近更新 更多