带有nodejs的流视频

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

我们如何在没有socket.io的节点上通过音频流传输视频。我已经尝试过iframe,但是它不符合我的要求。


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

请尝试这样

服务器js

const express = require('express')
const fs = require('fs')
const path = require('path')
const app = express()

app.use(express.static(path.join(__dirname, 'public')))

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname + '/index.htm'))
})

app.get('/video', function(req, res) {
  const path = 'assets/sample.mp4'
  const stat = fs.statSync(path)
  const fileSize = stat.size
  const range = req.headers.range

  if (range) {
    const parts = range.replace(/bytes=/, "").split("-")
    const start = parseInt(parts[0], 10)
    const end = parts[1]
      ? parseInt(parts[1], 10)
      : fileSize-1

    if(start >= fileSize) {
      res.status(416).send('Requested range not satisfiable\n'+start+' >= '+fileSize);
      return
    }

    const chunksize = (end-start)+1
    const file = fs.createReadStream(path, {start, end})
    const head = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/mp4',
    }

    res.writeHead(206, head)
    file.pipe(res)
  } else {
    const head = {
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    }
    res.writeHead(200, head)
    fs.createReadStream(path).pipe(res)
  }
})

app.listen(3000, function () {
  console.log('Listening on port 3000!')
})

html

<html>
  <head>
    <title>Video stream sample</title>
  </head>
  <body>
    <video id="videoPlayer" controls muted="muted" autoplay> 
      <source src="http://localhost:3000/video" type="video/mp4">
    </video>
  </body>
</html>

流程

  1. 发出请求后,我们获得文件的大小,并在else语句中发送视频的前几个块。

  2. 当我们开始观看视频时(通过localhost:3000 / video或从前端访问路由),随后会发出请求,这次是在标头中包含范围,以便我们知道我们的起点下一块。

  3. 再次读取文件以创建另一个流,并将新值作为开始和结尾(最有可能是请求标头中的当前部分以及视频的文件大小)。

  4. 我们通过应用公式将206标头响应设置为仅发送部分新生成的流

© www.soinside.com 2019 - 2024. All rights reserved.