从输入设备获取MediaStream

时间:2018-01-26 03:32:33

标签: javascript html5 ecmascript-6 getusermedia

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

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

这是我到目前为止:

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

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

我一直在getUserMedia检查MDN的官方文档  但没有任何东西与从约束到缓存的音频存储有关。

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

谢谢你。

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;

a fiddle因为stacksnippets不能与gUM一起工作......