Tips on saving an audio file to a Node server using blob or FormData

I am currently working on a project where I have a MedaRecroder stream recorded in audio/webm format. The stream is sent to a Node server, and while the file appears in the response under req.files, there seem to be encoding errors when playing it back.

My goal is to write the audio file to the server (preferably in .wav format, but webm will suffice) so that I can access and play the audio later on.

function onRecordingReady(e) {
  var audio = document.getElementById('audio');
  var tag = document.getElementById('tag').value
  audio.src = URL.createObjectURL(e.data);
  audio.play();
  var formData = new FormData()
   formData.append('source', e.data);
   formData.append('tag', tag);
  $.ajax({
    url: 'http://localhost:3300/api/kb8',
    type: "POST",
    data:formData,
    processData: false,
    contentType: false,
    success: function(data) {
            console.log(data);
    }
  });

When handling the post request on my server, I use the following code:

const express = require('express');
const bodyParser = require('body-parser');
const multer  = require('multer');
const fs = require('fs');
const wav = require('wav');
let upload = multer();
const app = express();
const PORT = process.env.PORT || 3300;
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res){
  res.send('hello world');
});   

app.post('/api/kb8', upload.any(), function(req, res) {
    let formData = req.body;
    let files = req.files;
    fs.writeFileSync('audio/audiotest.webm', req.files);
    console.log('form data', formData, 'file' , files);
    res.sendStatus(200);
});

Here's the console output related to the form data and files:

form data { tag: 'tag',  } file { fieldname: 'source',
  originalname: 'blob',
  encoding: '7bit',
  mimetype: 'audio/webm',
  buffer: <Buffer 1a 45 df a3 9f 42 86 81 01 42 f7 81 01 42 f2 81 04 42 f3 81 08 42 82 84 77 65 62 6d 42 87 81 04 42 85 81 02 18 53 80 67 01 ff ff ff ff ff ff ff 15 49 ... >,
  size: 14322 }

Answer №1

Finally, the solution has been uncovered!

When using Multer, an array of files is generated on the request object (req.files) to access the buffer and write to a file, one must execute the following code:

fs.writeFileSync('audio/audiotest.webm', req.files[0].buffer);

I trust this information proves to be beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Providing status after saving data to multiple databases in a single API request

I've primarily focused on frontend development, but recently I've ventured into backend development with Node.js and Mongoose. My current project involves creating a user in the database, generating an email token, and sending an email all within ...

Display the outcomes of two MongoDB queries simultaneously on a single page

As I dive into the world of MongoDB and Node.js/Express, I find myself struggling to fully grasp some of the concepts. Forgive my inexperience, but I haven't been able to locate a clear answer for what I'm trying to achieve. My goal is straight ...

After a certain period of time, the NodeJs exec() function ceases to create additional

I am in the process of developing a BLE scan module on nodeJs using Bluez. Below is the code snippet I have implemented: exec('sudo hcitool lescan --duplicates &', function (error, stdout, stderr) { }); exec('sudo hcitool lescan --dupl ...

Gone in a flash: the sudden vanishing act

I want to return error messages to the client without adding them to the URL. Here is my approach: exports.register = function(req, res) { if (req.body.password != req.body.password_repeat) { res.locals.err = 'Passwords must match.'; ...

Implement Next.js deployment on NGINX server with a 403 forbidden error

I am currently utilizing Next.js for the frontend and Django for the backend. During development, everything is functioning properly. However, when transitioning to production, I am encountering a 403 Forbidden Error related to /_next/static/chunks. It app ...

Unable to display image on HTML page in Sails JS

In my current project, I am utilizing Sails Js and Mongo DB for development. When a user uploads an image and content for a blog post, I store it in the images folder and save the file destination along with the content to MongoDB. My goal is to display bo ...

Tips for receiving string body parameters from Express routes in TypeScript instead of using the 'any' type?

I have a situation where I am passing a unique identifier called productId as a hidden input within a form: <form action="/cart" method="POST"> <button class="btn" type="submit">Add to Cart</button ...

Most efficient method: Exporting a DynamoDB table to a CSV file and saving it in an S3 bucket

Is there a more efficient way to export a DynamoDB table into an S3 bucket in CSV format? We already have a lambda function set up to update the DynamoDB table, but now we need to export the entire table. I came across a method of streaming directly from ...

The 'Alias[]' type does not share any properties with the 'Alias' type

I encountered an issue: The error message 'Type 'Alias[]' has no properties in common with type 'Alias'' appeared. Here is my Alias setup: alias: Alias = { id: 0, domain_id: 0, source: '', dest ...

Sorry, module 'ipfs' cannot be located. Please refer to web3.min.js:1:155 for more information

I am having trouble working with the node module ipfs.js as the console displays an error message: "Cannot find module 'ipfs'" Running on Ubuntu 16.04.4 LTS node --version = v8.10.0 npm --version = 5.6.0 ipfs version = 0.4.13 This is ...

When attempting to run the yarn build dist command, an error of type TypeError is encountered, stating that it is not possible to set the constructor property

Upon executing the following command in a GitHub workflow, I encountered this error: npm-run-all -p types transpile @internal_package: $ swc src --out-dir dist @internal_package: /home/runner/work/repo-name/repo-name/node_modules/ttypescript/lib/loadTypesc ...

Can caching be utilized to optimize the speed of npm ci?

Currently, the preferred method for installing node modules during Continuous Integration is by using npm ci. However, this process tends to be quite slow. Is there a way to accelerate the speed of npm ci by utilizing cache or avoiding the complete remo ...

expressjs templates

I am looking to implement two different layouts for the main page and admin page. What steps should I take to configure my code to achieve this? Here is my current configuration: app.configure(function(){ app.set('views', __dirname + ...

Creating Articles with Express.js and Body-parser

app.post("/article/submit", function(req, res) { let newPost = new Article(); newPost.title = req.body.title; newPost.author = req.body.author; newPost.content = req.body.content; newPost.save(function(error) { if (error) { console.log ...

The application is unable to interpret parameterized queries when utilizing Express and PostgreSQL

Complete newbie over here, I'm attempting to revamp my endpoint in order to enable sorting the return table by multiple columns read in via variables 'sort_by' and 'order', which have default values. However, when running the test ...

Differences Between Put and Post in Node.js

I am currently exploring NODEJS in conjunction with react. In a typical scenario, the request to edit posts would look like this: router.put("/:id", function(req, res) { Campground.findByIdAndUpdate(req.params.id, req.body.campground, function( e ...

In NodeJS, many middleware must be installed individually, such as bodyParser

While attempting to set up my application, which employs multiple middlewares including body-parser, I encountered the following error: Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please ...

The excessive length of Windows file paths makes it impossible to install packages with Node npm

Situation Having trouble using gulp and related front-end tools in Windows-based development environments due to long file paths when copying files from nested node_modules folders. Looking for a practical solution to address this issue on Windows without ...

The parcel command is unavailable

For my project, I have been using Parcel to bundle everything together. Now, as I am looking to deploy my application, I cloned my git repo with the React app and placed it in the Node server. I've tried various commands to install Parcel, but no mat ...

Basic server responding with "Error: Page not found"

I am encountering an issue with my server. Whenever I try to access localhost:3000, I receive an error message saying "Cannot GET /". The same problem occurs when I attempt to call /register. Does anyone have any suggestions on how to resolve this? Thank ...