0

Encountered the following problem: From the client side using websocket I drive the video bit by bit to the server:

mediaRecorder.ondataavailable = function (e) {
   if (ws && ws.readyState === WebSocket.OPEN && e.data && e.data.size > 0) {
      ws.send(e.data);
   }
   else {
      //...
   }
}
mediaRecorder.start(100);

On the server in a loop, I get these parts and write them to a file.

while (true)
{
   buffer = new ArraySegment<byte>(new byte[500000]);
   result = await socket.ReceiveAsync(buffer, CancellationToken.None);
   if (socket.State == WebSocketState.CloseReceived)
   {
      bw.Close();
      fs.Close();
      break;
   }
   if (Encoding.UTF8.GetString(buffer.Array, 0, result.Count) == "start record")
   {
      writeStatus = "start record";
      fullPath = $"{context.Server.MapPath("~")}{fileName}.{fileExt}";
      fs = new FileStream(fullPath, FileMode.Append, FileAccess.Write);
      bw = new BinaryWriter(fs);
      continue;
   }

   if (Encoding.UTF8.GetString(buffer.Array, 0, result.Count) == "stop record")
   {
      bw.Close();
      fs.Close();
      writeStatus = "none";
      continue;
   }

   if (writeStatus == "start record")
   {
      bw.Write(buffer.Array, 0, result.Count);
      pos += result.Count;
   }
}

The problem is that I need to keep writing videos to the same file every time the page is reloaded. As I understand it, just adding to the end of the file is not an option, since in this case all the bytes added are not played when playing the recorded video file. Tell me, please, how can I continue recording video in the same file?

Jericho
  • 11
  • 1
  • According to Google Translate, the title should read: *"How to continue recording a video stream (webm, vp8) to an existing file (using C #)"* but I'm not going to edit the question, because I'm not familiar with the language.. don't want to make interpretation mistakes. Jericho should do the edit.. – Goodies Jun 28 '20 at 12:05

1 Answers1

0

It is probably not possible, without going through a "video joining" process. I assume that the start of the stream from the browser includes a header that needs to be at the start of the file.

There are no simple algorithms or built-in .Net Framework tools that can help. It's best you try to use an external library or tool such as FFmpeg see Joining Multiple .wmv Files with C#

Video files are "container" formats that combine video and audio streams. You will find that multiple recording sessions are simply multiple "video file containers" that contain video and audio. If you keep track of where the start of the "video file container" is, you can feed that data to FFmpeg as separate files to be joined. You will not need to recompress the video or audio streams if they came from the same browser and have the same resolution, you should be able to simply "copy" those.

Kind Contributor
  • 17,547
  • 6
  • 53
  • 70