如何将我的cam流保存在服务器实时节点js中?

时间:2019-06-29 11:01:06

标签: node.js express getusermedia navigator mediadevices

如何将我的流的大块实时转换为blob保存在我的节点js服务器中

client.js |我将我的cam流作为二进制文件发送到我的节点js服务器

    handleBlobs = async (blob) => {

        let arrayBuffer = await new Response(blob).arrayBuffer()

        let binary = new Uint8Array(arrayBuffer)

        this.postBlob(binary)


    };

 postBlob = blob => {

        axios.post('/api',{blob})
            .then(res => {
                console.log(res)
            })
    };

server.js

app.post('/api', (req, res) => {
    console.log(req.body)
});

如何在视频录制结束时将传入的Blob或二进制文件存储到一个视频文件中。

2 个答案:

答案 0 :(得分:0)

在不尝试实现这一点的情况下(很抱歉,现在没有时间),我建议以下内容:

  1. 读入Node的Stream API,快速请求对象是http.IncomingMessage,它是可读流。可以将其通过另一个基于流的API进行管道传输。 https://nodejs.org/api/stream.html#stream_api_for_stream_consumers

  2. 读入Node的Filesystem API,它包含诸如fs.createWriteStream之类的函数,这些函数可以处理块流并将其追加到文件中,并具有您选择的路径。 https://nodejs.org/api/fs.html#fs_class_fs_writestream

  3. 完成到文件的流后,只要文件名具有正确的扩展名,文件就应该可以播放,因为通过浏览器发送的缓冲区只是二进制流。进一步阅读Node的Buffer API值得您花时间。 https://nodejs.org/api/buffer.html#buffer_buffer

答案 1 :(得分:0)

这似乎是How to concat chunks of incoming binary into video (webm) file node js?的副本,但当前没有可接受的答案。我也将我从该帖子中得到的答案也复制到了该帖子中:

我可以通过使用FileReader api在前端将其转换为base64编码来使其工作。在后端,从发送的数据块创建一个新的Buffer并将其写入文件流。我的代码示例中的一些关键事项:

  1. 我使用fetch是因为我不想插入axios
  2. 使用fetch时,必须确保在后端使用bodyParser
  3. 我不确定您要在块中收集多少数据(即,传递给start对象上的MediaRecorder方法的持续时间值),但是您需要确保您的后端可以处理传入的数据块的大小。我将我的数据确实设置为50MB很高,但这可能没有必要。
  4. 我从不明确地关闭写入流……您可以在/final路由中执行此操作。否则,createWriteStream默认为自动关闭,因此node进程将自动执行此操作。

下面的完整示例:

前端

const mediaSource = new MediaSource();
mediaSource.addEventListener('sourceopen', handleSourceOpen, false);
let mediaRecorder;
let sourceBuffer;

function customRecordStream(stream) {
  // should actually check to see if the given mimeType is supported on the browser here.
  let options = { mimeType: 'video/webm;codecs=vp9' };
  recorder = new MediaRecorder(window.stream, options);
  recorder.ondataavailable = postBlob 
  recorder.start(INT_REC)
};

function postBlob(event){
  if (event.data && event.data.size > 0) {
    sendBlobAsBase64(event.data);
  }
}

function handleSourceOpen(event) {
  sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
} 

function sendBlobAsBase64(blob) {
  const reader = new FileReader();

  reader.addEventListener('load', () => {
    const dataUrl = reader.result;
    const base64EncodedData = dataUrl.split(',')[1];
    console.log(base64EncodedData)
    sendDataToBackend(base64EncodedData);
  });

  reader.readAsDataURL(blob);
};

function sendDataToBackend(base64EncodedData) {
  const body = JSON.stringify({
    data: base64EncodedData
  });
  fetch('/api', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body
  }).then(res => {
    return res.json()
  }).then(json => console.log(json));
}; 

后端:

const fs = require('fs');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: "50MB", type:'application/json'}));

app.post('/api', (req, res) => {
  try {
    const { data } = req.body;
    const dataBuffer = new Buffer(data, 'base64');
    const fileStream = fs.createWriteStream('finalvideo.webm', {flags: 'a'});
    fileStream.write(dataBuffer);
    console.log(dataBuffer);
    return res.json({gotit: true});
  } catch (error) {
    console.log(error);
    return res.json({gotit: false});
  }
});