将 MediaRecorder blob 发送到服务器并在后端构建文件

Send MediaRecorder blobs to server and build file on backend

我正在使用 nodejs 和 SailsJs 开发网站。

我的objective是将MediaRecorder.ondataavailable事件生成的blob(returns小blob)发送到服务器,完成录制后在服务器上构建完整的文件进行存储.

在浏览器上,如果我将所有这些小 blob 推入一个数组然后执行此操作:

var blob = new Blob(recordedBlobs, {type: 'video/mp4'});

我得到了可以轻松上传到服务器并且完全可以播放的完整文件 blob。

我正在使用 ajax 将所有这些小 blob 发送到服务器,在服务器端我有这个在本地保存小 blob:

req.file('recordingPart').upload(async function...)

这会在我的 tmp 文件夹中创建一个文件来存储它,直到我想要 assemble 最终文件(我还发送了每个部分的索引以了解稍后组装的确切顺序)。

当用户结束录制时,我从前端发送另一个请求让我知道何时开始组装文件。

所以我使用 fs.readFile 将 tmp 文件内容放入数组中(根据我拥有的索引维护顺序),如下所示:

    const body = [];
    for (let i = 0; i < recParts.length; i++){
      body[recParts[i].part.index - 1] = await readFile(recParts[i].part.tmpPath, null);
    }

然后我使用以下方法创建文件:

const videoBuffer = Buffer.from(body);
    fs.writeFile(__dirname + '/../../.tmp/recording.mp4', videoBuffer, function(err) {
      if (err) console.log(err);
      console.log('File created');
    });

文件已创建但无法播放!!

我添加了一个 console.log(正文),我得到了这个:

BODY [ <Buffer 1a>,
  <Buffer 45 df a3 a3 42 86 81 01 42 f7 81 01 42 f2 81 04 42 f3 81 08 42 82 88 6d 61 74 72 6f 73 6b 61 42 87 81 04 42 85 81 02 18 53 80 67 01 ff ff ff ff ff ff ... >,
  <Buffer 46 24 82 00 20 00 00 00 00 01 21 e0 02 00 10 5c c2 62 44 f1 0d 55 69 04 a4 d1 b0 51 fc 4e 7c 5c 11 b5 f5 24 21 88 e5 26 68 d8 9b 10 3f c8 4b 15 3f 37 ... >,
  <Buffer 41 69 81 00 78 80 fb 83 7b 73 3e e7 41 8a 76 af 1f 22 60 92 f6 ac 22 40 eb ce fc 4f 43 5c 0c 45 73 e4 91 19 21 12 54 31 46 5d 0f bb a3 ba 27 cd 3d 5a ... >,
  <Buffer 41 7c 81 00 b3 80 fb 83 96 6f 9c eb f6 d4 d5 e1 49 65 66 6d 89 fd 17 f8 7d 7f fb a2 b1 a4 39 87 be 6f 24 d0 a6 b4 fa e7 74 1b 4e eb 40 8a dc a8 dc b6 ... >,
  <Buffer 41 12 82 00 b3 00 00 00 00 01 21 e0 08 00 40 15 c1 be e1 1d 56 a0 79 dc 5e a1 ca 50 dd 66 bc 34 21 8b 96 9c 90 b6 4e 51 48 f9 f5 0e 65 ec be 5e a2 8b ... >,
  <Buffer 44 3a 82 00 f0 00 00 00 00 01 21 e0 0c 00 60 27 28 d9 d7 a4 1b 6d 34 dc ca 9f c3 1e 08 7f 5d 16 a3 b9 7b 0f e5 1d 42 fb 94 4b 1e 29 93 91 57 15 cc 4a ... >,
  <Buffer 41 59 81 01 2c 80 fb 83 71 70 9a 9e 95 bc 32 37 da b1 95 1b 62 09 1e e3 98 31 81 65 a7 f0 2d 9f dc f7 c5 3c cc 46 40 a6 5b 8c 00 91 0a d2 65 ee cb cd ... >,
  <Buffer 45 22 82 01 2c 00 00 00 00 01 21 e0 10 00 80 5f d0 9e 92 ff ff 55 69 04 ed 7a 6d 5c ca c7 f8 21 f7 69 37 58 88 ae 65 d0 c9 bf ff d1 48 6d e8 4b 3a f0 ... >,
  <Buffer 41 54 81 01 68 80 fb 83 6f 6e 51 d9 a1 72 06 04 83 57 97 1f e4 10 00 ca 0e 87 d2 f9 ac 3c e9 c5 5f b9 1c 8d 32 ea 75 e5 0f 06 e0 55 1e 4d 40 8a af 63 ... >

欢迎任何建议

所以我通过执行以下操作解决了它(一旦我收到合并操作调用):

const dir = `${__dirname}/.tmp/`;
const fileName = getFileNameFromEvent(eventId);
const path = dir + fileName;
//First get the path for every file chunk ordered (otherwise it'll lose quality)
let recParts = await RecordingParts.find({
      where: {
        filename: fileName
      }
    }).sort('index ASC');

let wstream = fs.createWriteStream(path);
for (let i = 0; i < recParts.length; i++){
      let aux = await readFile(recParts[i].tmpPath, null);
      wstream.write(aux);
      //Delete chunks
      fs.unlink(recParts[i].tmpPath, (err) => {
        if (err) throw err;
      });
    }

    wstream.end();

//Utils function
const readFile = (path, opts = 'utf8') =>
  new Promise((res, rej) => {
    fs.readFile(path, opts, (err, data) => {
      if (err) rej(err);
      else res(data)
    })
  });

之后
wstream.end();

您将在 path

处获得合并文件

对于那些仍然对使用 MediaRecorder API 和 WebSockets 连续保存媒体流的流程感兴趣的人...

客户端:

const ws = new WebSocket(someWsUrl);
const mediaStream = new MediaStream();
const videoTrack = someStream.getVideoTracks()[0];
const audioTrack = someStream.getAudioTracks()[0];
mediaStream.addTrack(videoTrack);
mediaStream.addTrack(audioTrack);
const recorderOptions = {
  mimeType: 'video/webm',
  videoBitsPerSecond: 200000 // 0.2 Mbit/sec.
};
const mediaRecorder = new MediaRecorder(mediaStream, recorderOptions);
mediaRecorder.start(1000); // 1000 - the number of milliseconds to record into each Blob
mediaRecorder.ondataavailable = (event) => {
  console.debug('Got blob data:', event.data);
  if (event.data && event.data.size > 0) {
    ws.send(event.data);
  }
};

服务器端:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
wss.on('connection', (ws, req) => {
  const fileStream = fs.createWriteStream(filePath, { flags: 'a' });
  ws.on('message', message => {
    // Only raw blob data can be sent
    fileStream.write(Buffer.from(new Uint8Array(message)));
  });
});

如果对任何人有帮助,这就是我的解决方案:

我以二进制格式发送块(我选择了Uint8Array),并将接收到的数据打包后将每个块添加到服务器端的文件中(在相同的unsigned char解码中转换为二进制)

客户端Javascript:

let order=0;
mediaRecorder.ondataavailable = async (e) => {
    if(e.data && e.data.size > 0) {         
        var reader = new FileReader();
        reader.readAsArrayBuffer(e.data); 
        reader.onloadend = async function(event) {
            let arrayBuffer = reader.result;   
            let uint8View = new Uint8Array(arrayBuffer);
            let response = await fetch('save-video.php', {
                method: 'POST',                 
                body: JSON.stringify({
                    chunk: uint8View,
                    order: order
                })                  
            });
            order += 1;
        }

    }       
}

服务器端PHP:

<?php
    
$request = json_decode(file_get_contents("php://input"), true);
$chunk = $request['chunk'];
$order = $request['order'];
$binarydata = pack("C*", ...$chunk);
    
$filePath = "uploads/file.webm";
$out = fopen("{$filePath}", $order == 0 ? "wb" : "ab");
if ($out) {
    fwrite($out, $binarydata);
    fclose($out);
}

?>