mattdiamond / Recorderjs

A plugin for recording/exporting the output of Web Audio API nodes
4.16k stars 1.46k forks source link

How can I get the blob file (i.e recorder voice) to send the server #188

Open maneeshrao66 opened 6 years ago

maneeshrao66 commented 6 years ago

Hi, I have successfully recorded the audio voice. Now I want to send the recorded voice to server. So I have created a button i.e save and trying to get the recorded voice.

Where should I find the value which are recorded?

I tried below code:-

function createDownloadLink() {
  recorder && recorder.exportWAV(function(blob) {
    var url = URL.createObjectURL(blob);
    var li = document.createElement('span');
    var au = document.createElement('audio');
    var hf = document.createElement('a');
    var bt = document.createElement('button');

    au.controls = true;
    au.src = url;
    hf.href = url;
    hf.download = new Date().toISOString() + '.wav';
    hf.innerHTML = hf.download;
    li.appendChild(au);
    li.appendChild(hf);
    recordingslist.appendChild(li);
    bt.textContent = "Send post";

    bt.onclick =  function(){ saveRecording(blob); }
    li.appendChild(bt);
  });
}

function saveRecording(blob) {
  var file2 = new FileReader();
  file2.onloadend = function(e){
    $.ajax({
      url: "http://devapi.domani.com/webHooks/myTest",
      type: "POST",
      data: file2.result,
      processData: false,
      contentType : "text/plain"
    });
  } ;
  file2.readAsDataURL( blob );
octavn commented 6 years ago

$.ajax() is part of jQuery.

I would suggest using XMLHttpRequest instead like this:

bt.onclick = function(){
      var xhr=new XMLHttpRequest();
      xhr.onload=function(e) {
          if(this.readyState === 4) {
              console.log("Server returned: ",e.target.responseText);
          }
      };
      var fd=new FormData();
      fd.append("audio_data",blob, "filename.wav");
      xhr.open("POST","upload.php",true);
      xhr.send(fd);
}

Source: https://addpipe.com/blog/using-recorder-js-to-capture-wav-audio-in-your-html5-web-site/ Live demo: https://addpipe.com/simple-recorderjs-demo/

aschuss commented 5 years ago

works nicely in flask: //send wav blob to a function which invokes fetch rec.exportWAV(sendData); } function sendData(blob) { // sends data to flask url /messages as a post with data blob - in format for wav file, hopefully. it is a promise fetch("/messages", { method: "post", body: blob });

and in app.py:

@app.route('/messages', methods = ['POST']) def api_message(): f = open('./file.wav', 'wb') f.write(request.data) f.close() return "Binary message written!"

IAmSpring commented 5 years ago
  xhr.open("POST","upload.php",true);

I am having an issue with upload.php not being found. The public directory is available and the file(blob) is found if I copy the download link. This is the only PHP file in my entire stack so I am unsure if I need another PHP file to initialize it or if it is to be referenced in the main app.js.

wingedrasengan927 commented 4 years ago

works nicely in flask:

It's working perfect. Thank you so Much!

stofmiroune commented 4 years ago

works nicely in flask: //send wav blob to a function which invokes fetch rec.exportWAV(sendData); } function sendData(blob) { // sends data to flask url /messages as a post with data blob - in format for wav file, hopefully. it is a promise fetch("/messages", { method: "post", body: blob });

and in app.py:

@app.route('/messages', methods = ['POST']) def api_message(): f = open('./file.wav', 'wb') f.write(request.data) f.close() return "Binary message written!"

i got many errors while trying it , please is there a clean way to do it ?

susej2 commented 4 years ago

@maneeshrao66 you can do it using xhr request. I used it with C# as follows

Controller Name: Evaluation

C# Method:

    public ActionResult Upload(HttpPostedFileBase fileUpload0, string User, int Rec)

JS code: var xhr = new XMLHttpRequest(); var fd = new FormData(); fd.append("fileUpload0", blob); fd.append("User", document.getElementById("Id_Card").getAttribute("data-hiddenId")); fd.append("Rec", recnumber);

    xhr.open("POST", "https://yourserver/Evaluation/Upload");
    xhr.send(fd);

Hope this helps

stofmiroune commented 4 years ago

@maneeshrao66 you can do it using xhr request. I used it with C# as follows

Controller Name: Evaluation

C# Method:

    public ActionResult Upload(HttpPostedFileBase fileUpload0, string User, int Rec)

JS code: var xhr = new XMLHttpRequest(); var fd = new FormData(); fd.append("fileUpload0", blob); fd.append("User", document.getElementById("Id_Card").getAttribute("data-hiddenId")); fd.append("Rec", recnumber);

  xhr.open("POST", "https://yourserver/Evaluation/Upload");
  xhr.send(fd);

Hope this helps

Thanks, i just tried the first solution and it worked perfectly with flask . i had problems elsewhere but the senData worked just fine .

, thank you for your reply

saisriteja commented 4 years ago

works nicely in flask: //send wav blob to a function which invokes fetch rec.exportWAV(sendData); } function sendData(blob) { // sends data to flask url /messages as a post with data blob - in format for wav file, hopefully. it is a promise fetch("/messages", { method: "post", body: blob });

and in app.py:

@app.route('/messages', methods = ['POST']) def api_message(): f = open('./file.wav', 'wb') f.write(request.data) f.close() return "Binary message written!"

How do i call a function to access this data @aschuss

krishna-kumar-prathipati commented 3 years ago

works nicely in flask: //send wav blob to a function which invokes fetch rec.exportWAV(sendData); } function sendData(blob) { // sends data to flask url /messages as a post with data blob - in format for wav file, hopefully. it is a promise fetch("/messages", { method: "post", body: blob });

and in app.py:

@app.route('/messages', methods = ['POST']) def api_message(): f = open('./file.wav', 'wb') f.write(request.data) f.close() return "Binary message written!"

The recorder is not opening for me

perymerdeka commented 3 years ago

how to automatically download the blob file to the directory that has been specified?

perymerdeka commented 3 years ago

I found it here is an implementation using django

# views
def store_wav(request):
    if request.method == 'POST':
        # generate filename
        filename = datetime.now().strftime("%Y-%m-%d-%H-%M")

        f = open(f'{filename}.wav', 'wb')
        f.write(request.body)
        f.close()
        print('File Writted')
// app.js

// get cookie csrf from django
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// using fetch
function sendData(blob) {
    const csrf_token = getCookie('csrftoken')
    fetch('messages/', {
        headers: {"X-CSRFToken": csrf_token},
        method: 'post',
        body: blob,
    });
    console.log('success')
}