mediarecorder api通过Web Audio api播放(不是音频元素)

时间:2016-02-26 10:43:05

标签: javascript web-audio mediarecorder

我在从mediaRecorder api获取捕获的blob到Chrome中播放时遇到问题(它可以在Firefox中运行)。不确定它是否是Chrome中的错误。

报告的错误:

  

undefined:1 Uncaught(在promise中)DOMException:无法解码音频数据



 window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = (navigator.getUserMedia ||
                          navigator.webkitGetUserMedia ||
                          navigator.mozGetUserMedia ||
                          navigator.msGetUserMedia);

var context = new AudioContext();

var record = document.querySelector('#record');
var stop = document.querySelector('#stop');

if (navigator.getUserMedia) {
  console.log('getUserMedia supported.');

  var constraints = {
    audio: true
  };
  var chunks = [];

  var onSuccess = function(stream) {
    var mediaRecorder = new MediaRecorder(stream);
    record.onclick = function() {
      mediaRecorder.start();
      console.log(mediaRecorder.state);
      console.log("recorder started");
      record.style.background = "red";
      stop.disabled = false;
      record.disabled = true;
    }

    stop.onclick = function() {
      mediaRecorder.stop();
      console.log(mediaRecorder.state);
      console.log("recorder stopped");
      record.style.background = "";
      record.style.color = "";

      stop.disabled = true;
      record.disabled = false;
    }

    mediaRecorder.onstop = function(e) {
      console.log("onstop() called.", e);

      var blob = new Blob(chunks, {
        'type': 'audio/wav'
      });
      chunks = [];

      var reader = new FileReader();
      reader.addEventListener("loadend", function() {
        context.decodeAudioData(reader.result, function(buffer) {
          playsound(buffer);
        },
        function(e) {
          console.log("error ", e)
        });
      });
      reader.readAsArrayBuffer(blob);
    }

    mediaRecorder.ondataavailable = function(e) {
      chunks.push(e.data);
    }
  }

  var onError = function(err) {
    console.log('The following error occured: ' + err);
  }

  navigator.getUserMedia(constraints, onSuccess, onError);

} else {
  console.log('getUserMedia not supported on your browser!');
}

function playsound(thisbuffer) {
  var source = context.createBufferSource();
  source.buffer = thisbuffer;
  source.connect(context.destination);
  source.start(0);
}

<button id="record">record</button>
<button id="stop">stop</button>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

我完全按照原样使用了您的代码。在Chrome浏览器中一切正常。

在关闭错误https://codereview.chromium.org/1579693006/并将其添加到Chrome管道后,此问题已修复。

这不再是问题。

答案 1 :(得分:0)

要关闭此循环,我怀疑这是由于Chrome bug documented in a comment above引起的。看来此错误已在几年前修复,并且不再是问题,因为WebAudio现在使用ffmpeg进行解码。