正在将 HTML5 音频元素内容发送到 ajax POST

Sending HTML5 audio element content to ajax POST

我正在尝试为我的用户提供一种录制音频文件并将它们 post 到我的服务器的方法。我正在使用 Recorder.js for the recording part, and I can have an element populated by the user's (webrtc) recording as a blob generated by the javascript library. I am able to record and download the recording, just like on this demo: http://webaudiodemos.appspot.com/AudioRecorder/index.html

问题是,我如何才能将这段录音包含到 jQuery ajax post 中,而不是下载文件?目标是 post 将录音连同一些数据一起放在 a 上,接收服务器会将数据保存到数据库中,并将录音文件保存到磁盘上。

audioRecorder && audioRecorder.exportWAV(function (blob) {
        //Here we get the blob object url, which can be set as audio element source
        var url = URL.createObjectURL(blob);
        //Here we download the recording file
        audioRecorder.forceDownload(blob, 'output.wav');

        //I can set the audio element for pre-listening before user POSTs the form
        var au = $('#myaudioelement').attr("src",url);
    });

所以当用户发送 ajax POST 时,我需要将 'myaudioelement' 的内容添加到 $.ajax 调用中的数据字段,连同 的值之类的东西,我怎样才能做到这一点?

使用 jQuery 的内置 data 功能。

$.ajax({
    type: "POST",
    url: "/audio/save.php",
    data: audioRecorder.forceDownload(blob, 'output.wav')
});

或直接用POST:

$.post("/audio/save.php", {
    audio: audioRecorder.forceDownload(blob, 'output.wav')
});

请注意:鉴于音频文件是二进制数据,您可能希望在发送前对其进行 base64 编码,使其成为更易于处理的字符串。

感谢您的建议,它确实帮助我走上了正确的轨道,但是这就是我最终让事情按照我需要的方式工作的方式:

var recordingblob = null;

audioRecorder && audioRecorder.exportWAV(function (blob) {
    recordingblob = blob;
});

$("#myform").submit(function () {
    event.preventDefault();

    var formData = new FormData($(this)[0]);

    if (recordingblob) {
        var recording = new Blob([recordingblob], { type: "audio/wav" });
        formData.append("recording", recording);
    }
    $.ajax({
        url: myurl,
        type: 'POST',
        data: formData,
        //etc
    });
}

必须有其他方法来处理这个问题,但有了这个,我在服务器端只需很少的努力就可以将 wav 文件存储在我的服务器上,并且没有添加 js 库。