Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecorderJS uploading recorded blob via AJAX

I'm using Matt Diamond's recorder.js to navigate the HTML5 audio API, and feel this question probably has an apparent answer, but i'm unable to find any specific documentation.

Question: After recording a wav file, how can I send that wav to the server via ajax? Any suggestions???

like image 641
Todd Avatar asked Jan 14 '23 03:01

Todd


2 Answers

If you have the blob you'll need to turn it into a url and run the url through an ajax call.

// might be nice to set up a boolean somewhere if you have a handler object
object = new Object();
object.sendToServer = true;

// You can create a callback and set it in the config object.
var config = {
   callback : myCallback
}

// in the callback, send the blob to the server if you set the property to true
function myCallback(blob){
   if( object.sendToServer ){

     // create an object url
     // Matt actually uses this line when he creates Recorder.forceDownload()
     var url = (window.URL || window.webkitURL).createObjectURL(blob);

     // create a new request and send it via the objectUrl
     var request = new XMLHttpRequest();
     request.open("GET", url, true);
     request.responseType = "blob";
     request.onload = function(){
       // send the blob somewhere else or handle it here
       // use request.response
     }
     request.send();
   }
}

// very important! run the following exportWAV method to trigger the callback
rec.exportWAV();

Let me know if this works.. haven't tested it but it should work. Cheers!

like image 132
cameronroe Avatar answered Jan 25 '23 16:01

cameronroe


@jeff Skee's answer really helped but I couldn't grasps it at first, so i made something simpler with this little javascript function.

Function parameters
@blob : Blob file to send to server
@url : server side code url e.g. upload.php
@name : File index to reference at the server side file array

jQuery ajax function

function sendToServer(blob,url,name='audio'){
var formData = new FormData();
    formData.append(name,blob);
    $.ajax({
      url:url,
      type:'post',      
      data: formData,
      contentType:false,
      processData:false,
      cache:false,
      success: function(data){
        console.log(data);
      }
    });  }

Server side code (upload.php)

$input = $_FILES['audio']['tmp_name'];
$output = time().'.wav';
if(move_uploaded_file($input, $output))
    exit('Audio file Uploaded');

/*Display the file array if upload failed*/
exit(print_r($_FILES));
like image 32
Peter Moses Avatar answered Jan 25 '23 15:01

Peter Moses