首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从输入设备获取MediaStream

从输入设备获取MediaStream
EN

Stack Overflow用户
提问于 2018-01-26 11:32:33
回答 1查看 254关注 0票数 0

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

我正在做缓存录音和麦克风回放的工作;火狐和Chrome使用HTML5。

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

代码语言:javascript
复制
var constraints = {audio: true, video: false};

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

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

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

谢谢你。

EN

回答 1

Stack Overflow用户

发布于 2018-01-26 12:54:05

您可以简单地使用MediaRecorder API来完成这类任务。

为了只录制video+audio gUM流中的音频,您需要从gUM的MediaStream创建一个新的audioTrack:

代码语言:javascript
复制
// 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/');
  });
代码语言:javascript
复制
<video id="vid" controls autoplay></video>
<button id="stop_btn" disabled>stop</button>

由于堆栈片段在gUM中不能很好地工作,所以作为a fiddle ...

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48455423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档