MediaRecorder.ondataavailable - data size is alway

2019-06-06 10:31发布

问题:

I'm trying to record a user's voice in the browser using Web API Media Recorder.

At this stage, all I'm trying to do with the audio once recorded is add it to the source of an audio element and play it back.

When I stop the recorder, the 'ondataavailable' event is triggered, but the size of the data is 0, and nothing can be played back.

Here's where my code is at. I'm using React. Any ideas would be very much appreciated!

handleRecording (stream) {
 const recordedChunks = this.state.recordedChunks;
 const mediaRecorder = new MediaRecorder(stream)
 const _this = this;

 mediaRecorder.start();

 mediaRecorder.ondataavailable = function(e) {
  if (e.data.size > 0){
    recordedChunks.push(e.data);
    _this.setState({recordedChunks:recordedChunks});
  }
 }

 mediaRecorder.onstop = function(e) {
  if (recordedChunks){
    if(recordedChunks.length > 0) {
      const audio = document.querySelector('audio');
      audio.controls = true;
      const blob = new Blob(recordedChunks, { 'type' : 'audio/ogg; codecs=opus'      });
      const audioURL = window.URL.createObjectURL(blob);
      audio.src = audioURL;
    }
   }
  }

  this.setState({mediaRecorder:mediaRecorder});
},

startRecording () {
 const recording = true;
 this.setState({recording:recording});

 navigator.mediaDevices.getUserMedia({ audio: true, video: false })
    .then(this.handleRecording);
},

stopRecording () {
 const recording = false;
 const mediaRecorder = this.state.mediaRecorder;

 mediaRecorder.stop();
 this.setState({recording:recording, mediaRecorder:mediaRecorder});
}

Link to documentation: https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/ondataavailable

回答1:

OK I figured it out!

The reason the recording wasn't working was because I didn't have Chrome's experimental Web Platform Features enabled.

I learnt this by stumbling across this WebRTC Media Recorder samples site https://webrtc.github.io/samples/src/content/getusermedia/record/ - where recording also wasn't working. So I knew it wasn't to do with my specific code.

To enable the flag, go to chrome://flags/ in your Chrome browser, enable the flag and relaunch.