寻找使用媒体设备的经验:

我正在录制缓存并从麦克风源播放;使用HTML5的Firefox和Chrome。

这是我到目前为止的内容:

var constraints = {audio: true, video: false};

var promise = navigator.mediaDevices.getUserMedia(constraints);


我一直在查看MDN上getUserMedia上的官方文档
 但与将音频从约束存储到缓存无关。

以前在Stackoverflow上没有问过这样的问题;我想知道是否有可能。

谢谢。

最佳答案

您可以简单地将MediaRecorder API用于此类任务。

为了仅记录来自视频+音频gUM流的音频,您将需要根据gUM的audioTrack创建一个新的MediaStream:



// using async for brevity
async function doit() {
  // first request both mic and camera
  const gUMStream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
  // create a new MediaStream with only the audioTrack
  const audioStream = new MediaStream(gUMStream.getAudioTracks());
  // to save recorded data
  const chunks = [];
  const recorder = new MediaRecorder(audioStream);
  recorder.ondataavailable = e => chunks.push(e.data);
  recorder.start();
  // when user decides to stop
  stop_btn.onclick = e => {
    recorder.stop();
    // kill all tracks to free the devices
    gUMStream.getTracks().forEach(t => t.stop());
    audioStream.getTracks().forEach(t => t.stop());
  };
  // export all the saved data as one Blob
  recorder.onstop = e => exportMedia(new Blob(chunks));
  // play current gUM stream
  vid.srcObject = gUMStream;
  stop_btn.disabled = false;
}
function exportMedia(blob) {
  // here blob is your recorded audio file, you can do whatever you want with it
  const aud = new Audio(URL.createObjectURL(blob));
  aud.controls = true;
  document.body.appendChild(aud);
  document.body.removeChild(vid);
}
doit()
  .then(e=>console.log("recording"))
  .catch(e => {
    console.error(e);
    console.log('you may want to try from jsfiddle: https://jsfiddle.net/5s2zabb2/');
  });

<video id="vid" controls autoplay></video>
<button id="stop_btn" disabled>stop</button>





并且作为a fiddle,因为stacksnippets在gUM上不能很好地工作...

关于javascript - 从输入设备获取MediaStream,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48455423/

10-09 18:05