【问题标题】:Obtain MediaStream from input device从输入设备获取 MediaStream
【发布时间】:2018-01-26 03:32:32
【问题描述】:

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

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

这是我到目前为止所做的:

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

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

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

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

谢谢。

【问题讨论】:

  • 请详细说明您要做什么。缓存在哪里?为了什么?
  • 我正在尝试从麦克风录制 10 秒,存储它们,然后播放给用户。
  • 问题中的代码在哪里尝试记录音频输入?

标签: javascript html ecmascript-6 getusermedia


【解决方案1】:

您可以简单地使用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,因为 stacksn-ps 不能很好地与 gUM 配合使用......

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多