MediaRecorder.ondataavailable - 数据大小始终为 0 [英] MediaRecorder.ondataavailable - data size is always 0

查看:68
本文介绍了MediaRecorder.ondataavailable - 数据大小始终为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Web API Media Recorder 在浏览器中录制用户的声音.

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.

当我停止记录器时,触发了'ondataavailable'事件,但数据大小为0,无法回放.

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});
}

文档链接:https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/ondataavailable

推荐答案

好的,我想通了!

无法录制的原因是我没有启用 Chrome 的实验性网络平台功能.

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

我是通过在这个 WebRTC Media Recorder 示例站点 https 上偶然发现的://webrtc.github.io/samples/src/content/getusermedia/record/ - 录音也无法正常工作.所以我知道这与我的特定代码无关.

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.

要启用该标志,请在 Chrome 浏览器中访问 c​​hrome://flags/,启用该标志并重新启动.

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

这篇关于MediaRecorder.ondataavailable - 数据大小始终为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆