MediaRecorder.ondataavailable - data size is always 0

做~自己de王妃 提交于 2019-12-01 10:47:50

问题


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.



来源:https://stackoverflow.com/questions/41677776/mediarecorder-ondataavailable-data-size-is-always-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!