Javascript 将音频从MediaRecorder发送到服务器
我正在尝试编程一个客户端,它可以记录音频数据,然后发送到服务器 我在前端开发方面没有太多经验。我被告知要使用React,所以我尝试使用ReactMediaRecorder()Javascript 将音频从MediaRecorder发送到服务器,javascript,reactjs,audio,xmlhttprequest,blob,Javascript,Reactjs,Audio,Xmlhttprequest,Blob,我正在尝试编程一个客户端,它可以记录音频数据,然后发送到服务器 我在前端开发方面没有太多经验。我被告知要使用React,所以我尝试使用ReactMediaRecorder() 渲染(){ 返回( this.setState({audio:blobUrl})} render={({startRecording,stopRecording,mediaBlob})=>( 开始录音 {stopRecording();this.upload()}}>停止录制 )} /> ) } 上传(){ log(“使
渲染(){
返回(
this.setState({audio:blobUrl})}
render={({startRecording,stopRecording,mediaBlob})=>(
开始录音
{stopRecording();this.upload()}}>停止录制
)}
/>
)
}
上传(){
log(“使用blob调用上载”+this.state.audio)
//if(false){
如果(this.state.audio!=null){
log(“转到这里,音频类型为”+this.state.audio)
var xhr=new XMLHttpRequest();
var filename=new Date().toISOString();
xhr.onload=函数(e){
if(this.readyState==4){
log(“服务器返回:”,e.target.responseText);
}
};
var fd=新FormData();
fd.append(“audio_data”,this.state.audio,filename);
xhr.open(“POST”http://127.0.0.1:3000“,对);
xhr.send(fd);
}
}
起初它看起来很简单。但我不明白为什么我不能发送mediaBlob。formData.append说,this.state.audio
不是Blob
类型。所以我在控制台日志中检查了它的类型,发现它是stringContent
类型。我尝试使用new 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();
}
}
现在它工作得很好
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();
}
}