将 Motion-JPEG 实时视频流从 Express 传输到 React

问题描述 投票:0回答:1

我的服务器上有一个网络摄像机,它有一个http链接来访问实时视频:

http://ip/video1.mjpg.

我是否可以通过 Express 将 .mjpg 流式传输到 React 前端?我已经成功使用 Express 从服务器发送正常视频。

request(location).pipe(res) 

早些时候,当我使用 RTSP 链接而不是 http 链接时,我曾经使用 ffmpeg 和 PHP 作为后端进行流式传输到前端,但现在我尝试通过 Express 直接从摄像头流式传输到前端 REACT。

node.js express video-streaming html5-video
1个回答
0
投票

您可以尝试在服务器端使用本机http模块。当客户端从 React 前端访问此路由时,服务器将使用 http.get 方法从 IP 摄像头获取 MJPEG 流。然后,MJPEG 帧可以流式传输到客户端,从而保持连续的视频输入。像这样的东西应该有效,

app.get('/video-stream', (req, res) => {
  const cameraUrl = 'http://ip/video1.mjpg'

  http.get(cameraUrl, cameraResponse => {
    // set the appropriate content type for MJPEG streaming
    res.writeHead(200, {
      'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary'
    })

    cameraResponse.on('data', chunk => {
      res.write('--myboundary\r\n')
      res.write('Content-Type: image/jpeg\r\n')
      res.write(`Content-Length: ${chunk.length}\r\n\r\n`)
      res.write(chunk, 'binary\r\n')
    })

    cameraResponse.on('end', () => {
      res.end()
    })
  }).on('error', error => {
    // handle error here ...
  })
})

在 React 中,你可以使用视频元素之类的东西来显示流,

const VideoStream = () => {
  const videoUrl = 'http://localhost:3001/video-stream' // Your server URL goes here ...

  return (
    <div>
      <h1>Live Video Stream</h1>
      <video width="640" height="480" controls>
        <source src={videoUrl} type="video/mp4" />
        Your browser does not support the video tag.
      </video>
    </div>
  )
}

export default VideoStream
© www.soinside.com 2019 - 2024. All rights reserved.