是否可以使用MediaRecorder()获得音频数据的原始值

问题描述 投票:0回答:2

我正在将MediaRecorder()与getUserMedia()一起使用,以记录来自浏览器的音频数据。它可以工作,但是记录的数据以Blob格式记录。我想获取原始音频数据(幅度),而不是Blob。有可能做到吗?

我的代码如下:

  navigator.mediaDevices.getUserMedia({audio: true, video: false}).then(stream => {
    const recorder = new MediaRecorder(stream);
    recorder.ondataavailable = e => {
      console.log(e.data); // output: Blob { size: 8452, type: "audio/ogg; codecs=opus" }
    };
    recorder.start(1000); // send data every 1s
  }).catch(console.error);
javascript webrtc mediarecorder web-mediarecorder
2个回答
1
投票

MediaRecorder对创建文件很有用;如果您想进行音频处理,Web Audio将是更好的方法。请参阅this HTML5Rocks tutorial,其中显示了如何使用Web Audio中的createMediaStreamSource将getUserMedia与Web Audio集成。


0
投票

不需要MediaRecorder。使用网络音频访问原始数据值,例如like this

navigator.mediaDevices.getUserMedia({audio: true})
.then(spectrum).catch(console.log);

function spectrum(stream) {
  const audioCtx = new AudioContext();
  const analyser = audioCtx.createAnalyser();
  audioCtx.createMediaStreamSource(stream).connect(analyser);

  const canvas = div.appendChild(document.createElement("canvas"));
  canvas.width = window.innerWidth - 20;
  canvas.height = window.innerHeight - 20;
  const ctx = canvas.getContext("2d");
  const data = new Uint8Array(canvas.width);
  ctx.strokeStyle = 'rgb(0, 125, 0)';

  setInterval(() => {
    ctx.fillStyle = "#a0a0a0";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
 
    analyser.getByteFrequencyData(data);
    ctx.lineWidth = 2;
    let x = 0;
    for (let d of data) {
      const y = canvas.height - (d / 128) * canvas.height / 4;
      const c = Math.floor((x*255)/canvas.width);
      ctx.fillStyle = `rgb(${c},0,${255-x})`;
      ctx.fillRect(x++, y, 2, canvas.height - y)
    }

    analyser.getByteTimeDomainData(data);
    ctx.lineWidth = 5;
    ctx.beginPath();
    x = 0;
    for (let d of data) {
      const y = canvas.height - (d / 128) * canvas.height / 2;
      x ? ctx.lineTo(x++, y) : ctx.moveTo(x++, y);
    }
    ctx.stroke();
  }, 1000 * canvas.width / audioCtx.sampleRate);
};
<div id="div"></div>
© www.soinside.com 2019 - 2024. All rights reserved.