Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

node.js - Blob saved as [object Object] Nodejs

I want to record audio from the microphone with HTML5, then send it to the server to be saved. Currently however, the saved file just contains [object Object]

Here are some snippets of my code.

Frontend:

console.log(blob);
$http.post('/api/save_recording', blob)
  .success(function(new_recording) {
    console.log("success");
  })

The log prints:

Blob {type: "audio/wav", size: 237612, slice: function}
success

Backend:

exports.saveRecording = function(req, res) {
  console.log(req.body);

  fs.writeFile("temp/test.wav", req.body, function(err) {
    if(err) {
      console.log("err", err);
    } else {
      return res.json({'status': 'success'});
    }
  }) 
}

The log prints: { type: 'audio/wav', size: 786476 }

Can you tell me why this isn't working, and how to fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I finally got this working. The approach to get this to work is to encode the blob on the client, and decode it on the server.

Frontend:

// converts blob to base64
var blobToBase64 = function(blob, cb) {
  var reader = new FileReader();
  reader.onload = function() {
    var dataUrl = reader.result;
    var base64 = dataUrl.split(',')[1];
    cb(base64);
  };
  reader.readAsDataURL(blob);
};

blobToBase64(blob, function(base64){ // encode
  var update = {'blob': base64};
  $http.post('/api/save_recording', update)
    .success(function(new_recording) {
      console.log("success");
    });
});    

Backend:

exports.saveRecording = function(req, res) {
  var buf = new Buffer(req.body.blob, 'base64'); // decode
  fs.writeFile("temp/test.wav", buf, function(err) {
    if(err) {
      console.log("err", err);
    } else {
      return res.json({'status': 'success'});
    }
  }); 
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...