将音频从ReactMediaRecorder发送到服务器

时间:2019-09-04 11:12:00

标签: javascript reactjs audio xmlhttprequest blob

我正在尝试对客户端进行编程,该客户端可以记录音频数据,然后将其发送到服务器。

我在前端开发方面经验不足。有人告诉我使用React,所以我尝试使用ReactMediaRecorder(https://github.com/avasthaathraya/react-media-recorder)。


  render () {
        return (
            <ReactMediaRecorder
                audio
                whenStopped={blobUrl=>this.setState({audio: blobUrl })}
                render={({startRecording, stopRecording, mediaBlob }) => (
                    <div>
                        <button id="recorder" className="button" onClick={startRecording}>Start Recording</button>
                        <button className="button" onClick={() => {stopRecording();this.upload()}}>Stop Recording</button>
                        <audio id="player" src={mediaBlob} controls />
                    </div>
                )}
            />
        )
    }



    upload() {
        console.log("upload was called with blob " + this.state.audio)
        //if (false) {
        if (this.state.audio != null) {
            console.log("got here, type of audio is " + this.state.audio)


            var xhr = new XMLHttpRequest();
            var filename = new Date().toISOString();
            xhr.onload = function (e) {
                if (this.readyState === 4) {
                    console.log("Server returned: ", e.target.responseText);
                }
            };
            var fd = new FormData();
            fd.append("audio_data", this.state.audio, filename);
            xhr.open("POST", "http://127.0.0.1:3000", true);
            xhr.send(fd);
        }
    }

起初,这似乎非常简单。但是我不明白为什么我不能发送mediaBlob。 formData.append说,this.state.audio不是类型Blob。因此,我在控制台日志中检查了它的类型,发现它的类型为stringContent。我尝试使用new Blob()从中创建一个Blob,但失败了。我也找不到此类信息。

有人知道该怎么办吗?

1 个答案:

答案 0 :(得分:0)

好吧,我终于明白了。错误是mediaBlob实际上不是blob,而是blob Url。因此,首先我们需要加载它,然后才能发送它。我将上传功能更改为:

upload(mediaBlob) {
    if (this.state.audio != null) {
        //load blob
        var xhr_get_audio = new XMLHttpRequest();
        xhr_get_audio.open('GET', mediaBlob, true);
        xhr_get_audio.responseType = 'blob';
        xhr_get_audio.onload = function(e) {
            if (this.status == 200) {
                var blob = this.response;
                //send the blob to the server
                var xhr_send = new XMLHttpRequest();
                var filename = new Date().toISOString();
                xhr_get_audio.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_send.open("POST", "http://localhost/uploadAudio", 
                true);
                xhr_send.send(fd);
            }
        };
        xhr_get_audio.send();
    }
} 

现在可以正常工作了。