Send MediaRecorder blobs to server and build file on backend

前端 未结 3 772
悲哀的现实
悲哀的现实 2021-02-04 15:08

I\'m working on a website using nodejs and SailsJs.

My objective is send the blobs generated by MediaRecorder.ondataavailable event (which returns small blobs) to the se

3条回答
  •  执笔经年
    2021-02-04 15:27

    For those who are still interesting in the flow of the continuous saving of the media stream using MediaRecorder API and WebSockets...

    Client side:

    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);
      }
    };
    

    Server side:

    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)));
      });
    });
    

提交回复
热议问题