Sending and handeling wav file to NodeJS

1.7k views Asked by At

there are several posts around this topic but I still have not been able to debug my code ,e.g. Sending HTML5 audio element content to ajax POST

Currently I have a client that allows the user to record audio using recorder.js. Then I want to to take the resulting wav file which is stored in a blob and send it to my server side code and store it in mongo.

   rec.exportWAV(sendToBackEnd);
}


function sendToBackEnd(blob){
    var blob = blob;
    console.log(blob)
    var fd = new FormData();
    fd.append('fname', 'test.wav');
    fd.append('data', blob);
    // fd.append('data', blob);
    $.ajax({
        url: '/recordings',
        type: 'POST',
        data: fd,
        processData: false,
        // contentType: "audio/wav"
    }).done(function(data) {
       console.log(data);
    });
}

I have read in several posts that I should set contentType to false however then the req.body is empty.

On the server side I have the following code.

var mongoose=       require('mongoose');
var express =       require('express');
var app     =       express();
var http    =       require('http');
var port    =       3000;
var bodyParser=     require('body-parser');


app.use(express.static('public'))
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({extended:true,limit:'50mb'}));
// app.use(bodyParser.json({ limit: '50mb' }));
// app.use(bodyParser.raw({ type: 'audio/wav',extended:true, limit: '50mb' }));

app.get('/',function(req,res){
    res.render('home.html')
});
app.get('/recordings/new',function(req,res){
    res.render('new.html')
});


app.post('/recordings',function(req,res){
    var recording = req.body
    console.log(req.body)
});

// app.get('/recordings',function(req,res){
//  res.render('index.html')
// });






mongoose.connect("mongodb://localhost:27017/sensor",{ useNewUrlParser: true },function(){
    console.log('database is connected');
});

app.listen(port, function(){
    console.log('sensor server is running')
    });

Any help on this would bee highly appriciated. Thanks!

1

There are 1 answers

0
Jeremy Jones On

Here is how I got audio recording, uploading & storing working using recorder.js with express server.

Client

I'm not using jQuery below, only native XMLHttpRequest:

this.recorder.stop().then(({ blob }) => {
  if (blob.size === 44) { // 44 bytes means something is wrong. reload to fix
    if (window.confirm('Sorry, no audio was captured. Click OK to reload the page.'))
      window.location.reload();
    else return;
  }

  const fd = new FormData(),
    xhr = new XMLHttpRequest();

  fd.append("audioData", blob);

  xhr.onreadystatechange = r => {
    if (xhr.status !== 200) { window.alert("Sorry, something went wrong"); return }

    const response = JSON.parse(r.target.response);
    console.info(`Ok, audio uploaded!`, response);
  };
  xhr.open("POST", "https://my.audio.server/upload", true);
  xhr.send(fd);
});

Server

On my server I'm using express but not MongoDB, but it looks like your server-side issue is more in getting the audio data that's been uploaded. Here is how I do it:

const fs = require("fs"),
  fileUploader = require("multer")({ dest: "/tmp/" });

app.post("/upload", fileUploader.single("audioData"), (req, res) => {
  const temporaryFilename = req.file.path,
    wavData = fs.readFileSync(temporaryFilename),
    bytes = fs.statSync(temporaryFilename)["size"];

  // do something with wavData

  return res.json({ ok: true, bytes, at: new Date() });
});