Home > OS >  Save the recorded javascript audio file locally and send it through ajax to flask backend
Save the recorded javascript audio file locally and send it through ajax to flask backend

Time:08-16

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <title>Recorder App</title>
  </head>
  <h2>Recorder App</h2>
  <p>
    <button type="button" id="record">Record</button>
    <button type="button" id="stopRecord" disabled>Stop</button>
  </p>
  <p>
    <audio id="recordedAudio"></audio>
  </p>
 
   
  <script>
    navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
      handlerFunction(stream);
    });

    function handlerFunction(stream) {
      rec = new MediaRecorder(stream);
      rec.ondataavailable = (e) => {
        audioChunks.push(e.data);
        if (rec.state == "inactive") {
          let blob = new Blob(audioChunks, { type: "audio/mp3" });
          recordedAudio.src = URL.createObjectURL(blob);
          recordedAudio.controls = true;
          recordedAudio.autoplay = true;
          sendData(blob);
        }
      };
    }

    function sendData(data) {}
    record.onclick = (e) => {
      record.disabled = true;
      record.style.backgroundColor = "blue";
      stopRecord.disabled = false;
      audioChunks = [];
      rec.start();
    };
    stopRecord.onclick = (e) => {
      record.disabled = false;
      stop.disabled = true;
      record.style.backgroundColor = "red";
      rec.stop();
    };
  </script>
  
 

How can i make this save the recorded javascript file locally and pass it through ajax to backend flask?

The code is running fine but it is not saving the file locally also i tried to pass the file directly through ajax to flask backend but the file that i am receiving in flask is empty.

Also it would be great if i can convert that file to .wav as i am using this for ASR project.

CodePudding user response:

If you save the file locally (with the purpose of send it to the server), the user will need to explicitly select the file to send it to the server.

You need to place audioChunks globally to be available for the rest of the functions:

 audioChunks = [];

record.onclick = (e) => {
  record.disabled = true;
  record.style.backgroundColor = 'blue';
  stopRecord.disabled = false;
  // audioChunks = [];
  rec.start();
};

Also the MediaRecorder need to be in the available in the scope for stopRecord.onclick(), take a look here:

MDN MediaRecorder

Take a look to this post for the file upload How do I upload a file with the JS fetch API?

The conversion of the file to .wav need to be done in the server side

  • Related