【问题标题】:RecorderJS uploading recorded blob via AJAXRecorderJS 通过 AJAX 上传记录的 blob
【发布时间】:2013-02-07 12:11:02
【问题描述】:

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

问题:录制了一个wav文件后,如何通过ajax将那个wav发送到服务器?有什么建议吗???

【问题讨论】:

    标签: ajax html audio upload recorder


    【解决方案1】:

    以上两个解决方案都使用 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

    【讨论】:

      【解决方案2】:

      @jeff Skee 的 回答确实很有帮助,但一开始我无法理解,所以我用这个小 javascript 函数做了一些简单的事情。

      功能参数
      @blob : 发送到服务器的 Blob 文件
      @url : 服务器端代码 url 例如上传.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】:

        如果您有 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();
        

        让我知道这是否有效。尚未对其进行测试,但应该可以。干杯!

        【讨论】:

        • @Todd 这对你有用吗?我正在尝试做同样的事情,请参阅stackoverflow.com/questions/15795678/…
        • 非常感谢。我忘记选择那个答案是正确的,但是是的,我已经忘记了是否需要调整。我很确定这段代码很有魅力!
        • 我正在尝试完成同样的工作,但老实说,我不明白示例代码是如何工作的。为什么我们首先向我们生成的 URL 发送请求? request.onload() 应该做什么?为什么我们不能将 blob 直接放入请求中?非常感谢您的解释,在此先感谢!
        • XMLHttpRequests 仅请求 url。在这种情况下,必须通过对象 URL 引用 blob,XHR 将通过 .send() 加载它 onload 处理程序是您可以访问响应(blob 数据)developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
        • 此代码不会将 blob 文件上传或发布到服务器。正如我所看到的,它只是将 blob 转换为对象 URL 并返回(参见this answer),这不是所要求的。下面的 Jeff Skee 和 Peter Moses Mohemos 的答案是正确的
        【解决方案4】:

        我还花了很多时间来尝试实现您在这里想要做的事情。只有在实现 FileReader 并调用 readAsDataURL() 将 blob 转换为数据后,我才能成功上传音频 blob 数据:表示文件数据的 URL(查看 MDN FileReader)。您还必须POST,而不是GET FormData。这是我的工作代码的范围 sn-p。享受吧!

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

        【讨论】:

        • FormData.append 也接受 blob,因此您可以将音频作为文件发送。 formData.append('audio', blob, 'filename.ext');
        • @Musa 当我将 blob 附加到 FormData 时,它不会显示在服务器上的 FormCollection 对象中(ASP.NET MVC3)。很想知道是否有办法将 blob 直接传递到服务器,而不必先使用 FileReader 读取它,但在我所有的研究中,我还没有找到一种方法。
        • 它将显示为一个文件。您可以使用XMLHttpRequest.send 直接发送 blob,但我不知道您将如何在 asp.net 上阅读。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-01
        • 2019-12-11
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多