RecorderJS通过AJAX上传记录的blob

时间:2013-02-22 00:09:21

标签: ajax html5 audio upload recorder

我正在使用Matt Diamond的recorder.js来浏览HTML5音频API,并且觉得这个问题可能有明显的答案,但我找不到任何具体的文档。

问题:录制wav文件后,如何通过ajax将该wav发送到服务器?任何建议???

4 个答案:

答案 0 :(得分:5)

如果你有blob,你需要把它变成一个url并通过ajax调用运行url。

// 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();

让我知道这是否有效..没有测试过,但它应该工作。干杯!

答案 1 :(得分:2)

我也花了很多时间试图达到你想要做的事情。我只能在实现FileReader并调用readAsDataURL()将blob转换为数据后才能成功上传音频blob数据:表示文件数据的URL(签出MDN FileReader)。您还必须 POST ,而不是 GET FormData。这是我的工作代码的范围片段。享受!

function uploadAudioFromBlob(assetID, blob)
{
    var reader = new FileReader();

    // this is triggered once the blob is read and readAsDataURL returns
    reader.onload = function (event)
    {
        var formData = new FormData();
        formData.append('assetID', assetID);
        formData.append('audio', event.target.result);
        $.ajax({
            type: 'POST'
            , url: 'MyMvcController/MyUploadAudioMethod'
            , data: formData
            , processData: false
            , contentType: false
            , dataType: 'json'
            , cache: false
            , success: function (json)
            {
                if (json.Success)
                {
                    // do successful audio upload stuff
                }
                else
                {
                    // handle audio upload failure reported
                    // back from server (I have a json.Error.Msg)
                }
            }
            , error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error! '+ textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
                // handle audio upload failure
            }
        });
    }
    reader.readAsDataURL(blob);
}

答案 2 :(得分:1)

@jeff Skee的答案确实有帮助,但起初我无法理解,所以我通过此小javascript函数使事情变得更简单。

功能参数
@blob:要发送到服务器的Blob文件
@url:服务器端代码url,例如upload.php
@name:在服务器端文件数组上引用的文件索引

jQuery ajax函数

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);
      }
    });  }

服务器端代码(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));

答案 3 :(得分:0)

以上两种解决方案都使用jQuery和$.ajax()

这是原生XMLHttpRequest解决方案。只要在有权访问blob元素的地方运行此代码,即可:

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");
xhr.open("POST","upload.php",true);
xhr.send(fd);

服务器端upload.php很简单:

$input = $_FILES['audio_data']['tmp_name']; //temporary name that PHP gave to the uploaded file
$output = $_FILES['audio_data']['name'].".wav"; //letting the client control the filename is a rather bad idea

//move the file from temp name to local folder using $output name
move_uploaded_file($input, $output)

source | live demo