我试图创建一个简单的React应用程序,您可以在其中录制音频片段并进行播放。我可以使记录功能正常工作,但我不确定如何将该数据传递给我的停止onclick。这就是我到目前为止所拥有的:
export default class SongRecorder extends React.Component{
constructor(){
super();
this.state = {
record: false,
songData: {}
}
this.recordSong = this.recordSong.bind(this);
this.stopRecord = this.stopRecord.bind(this);
}
recordSong(e){
e.preventDefault();
navigator.mediaDevices.getUserMedia({
audio: true
})
.then(function(stream){
const recorder = new MediaRecorder(stream);
recorder.start();
console.log(recorder.state);//this will tell us if recording is happening or not
console.log("recorder started");
//as recording happens, we need to collect the audio data with ondataavailable
const chunks = [];
recorder.ondataavailable = function(e){
chunks.push(e.data);
}
})
this.setState({
record: true,
})
}
stopRecord(e){
e.preventDefault();
this.setState({
record: false,
})
}

我试着在recordSong中写一个if语句,这样如果record设置为false,它会停止录音机并将songData设置为块,但我认为这不起作用。
function stop(recorder){
if(this.state.record === false){
recorder.stop();
this.setState({
songData: chunks
})
}
};

答案 0 :(得分:0)
创建另外一个名为chunks
的状态,然后在响应中设置块:
recordSong(e){
e.preventDefault();
navigator.mediaDevices.getUserMedia({
audio: true
})
.then(function(stream){
const recorder = new MediaRecorder(stream);
recorder.start();
console.log(recorder.state);//this will tell us if recording is happening or not
console.log("recorder started");
//as recording happens, we need to collect the audio data with ondataavailable
recorder.ondataavailable = function(e){
this.setState({chunks:chunks.push(e.data)});
}
})
this.setState({
record: true,
})
}
function stop(recorder){
if(this.state.record === false){
recorder.stop();
this.setState({
songData: this.state.chunks
})
}
};