How to save video recorded with MediaRecorder API to php server?

2.5k views Asked by At

I can record a video with the webcam, play the resulting blob on the browser and download it on the local machine, but when i save the file to the server it is unreadable. I have tried sending the chunks to the server and concatenate them there, and also sending the whole blob, but the result is the same (unreadable video). I first read the blobs with a FileReader(), which gives a base64 result, then send it to the server, where i base64_decode() it and save it to a folder.

JS code:

var reader = new FileReader(); 
reader.readAsDataURL(chunks[index]);
reader.onload = function () {
  upload(reader.result, function(response){
    if(response.success){
      // upload next chunk
    }
  });
};

on the server:

$json = json_decode( $request->getContent(), true );
$chunk = base64_decode( $json["chunk"] );
// all chunks get
file_put_contents("/uploadDirecotry/chunk".$json['index'].".webm", $json["chunk"]);

When all chunks are uploaded:

for ($i = 0; $i < $nrOfChunks; $i++) {
  $file = fopen("/uploadDirectory/chunk".$i.".webm", 'rb');
  $buff = fread($file, 1024000);
  fclose($file);

  $final = fopen("/processed/".$video->getFileName()."-full.webm", 'ab');
  $write = fwrite($final, $buff);
  fclose($final);

  unlink("/uploadDirectory/chunk".$i.".webm");
}

I don't know what i am doing wrong. I've been trying for more than a week to make it work, but it won't. Please help!

1

There are 1 answers

1
nithinTa On BEST ANSWER

you have to save decoded chunk

instead of this

file_put_contents("/uploadDirecotry/chunk".$json['index'].".webm", $json["chunk"]);

use this

file_put_contents("/uploadDirecotry/chunk".$json['index'].".webm", $chunk);

Also i suggest, please open final file before your "for loop" in write mode and close it after loop, instead of reopen every time in "for loop".