Sether's
Sether's

Reputation: 31

Sending Audio Blob data from a React frontend to a Express backend

so I am running into an issue with sending audio(created in the browser) to my backend to be stored in a database. I am using React on the Front-end and using the Web Audio API to allow a user to create audio. When I send it, the backend just receives an empty object. Does anyone know how I can get the data to persist so that it can be stored in the database to be played later?

mediaRecorderOnStop() {
    console.log("data available after MediaRecorder.stop() called.");
    const clipName = prompt('Enter a name for your sound clip?', 'My unnamed clip')

    //creating new blob object
    const blob = new Blob(this.state.chunks, { 'type': 'audio/ogg; codecs=opus' });

    //sending data to the backend
    uploadDocumentRequest(this.props.createClip(blob, clipName))

    this.setState({
        chunks: []
    })
    console.log("recorder stopped");
}

//makes a api post request to server
export function uploadDocumentRequest(data) {
    axios.post('/api/createAudio', data)
        .then(response => console.log(uploadSuccess(response)))
        .catch(error => console.log(uploadFail(error)));

}

Here is an image of my code

Upvotes: 3

Views: 5739

Answers (1)

user2216455
user2216455

Reputation: 31

assuming you are sending JSON, you won't be able to send a binary data to the server.

you have to encode you data with multipart/formdata

for that you should construct FormData object which later can be sent via XHR or Fetch API

  var fd = new FormData();
  var fd.append('audio', blob);

  fetch(apiUrl + '/api/createAudio', {
    headers: { Accept: "application/json" },
    method: "POST", body: fd
  });

the request Content-Type: multipart/formdata header will be automatically set

you have to make sure that you web app is able to process multipart/formadata encoded requests

Upvotes: 3

Related Questions