我正在尝试对客户端进行编程,该客户端可以记录音频数据,然后将其发送到服务器。
我在前端开发方面经验不足。有人告诉我使用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,但是失败了。我也找不到此类信息。有人知道该怎么办吗?
最佳答案
好吧,我终于明白了。错误是,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();
}
}
现在工作正常。
关于javascript - 将音频从ReactMediaRecorder发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57787174/