MediaRecorder API simple example / “hello world”

时间秒杀一切 提交于 2019-12-25 14:58:09

问题


Here's a simple example for the MediaRecorder API:

(async function() {
  let chunks = [];
  let stream = await navigator.mediaDevices.getUserMedia({ audio:true, video:false });
  let mediaRecorder = new MediaRecorder(stream);

  // record for 3 seconds:
  mediaRecorder.start();
  setTimeout(() => { mediaRecorder.stop(); }, 3000)

  mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); };
  mediaRecorder.onstop = async function() {
    let blob = new Blob(chunks, { type: mediaRecorder.mimeType });
    let audioURL = window.URL.createObjectURL(blob);
    let arrayBuffer = await (await fetch(audioURL)).arrayBuffer();
    let audioBuffer = await (new AudioContext()).decodeAudioData(arrayBuffer);
    // ... do stuff with audioBuffer
  };
})();

This doesn't currently work in chrome due to a known bug with the opus codec. It looks like it has been fixed recently so it should reach the stable release within a couple of months (I think?).

So my question is: Is the "hello world" that I've presented above correct? It seems to work fine on firefox, and will hopefully work on chrome soon, but I'm not exactly sure about all the nitty gritty details of the spec and I just want to make sure I'm doing everything right. Some sub-questions regarding the correctness of the example code:

  • In Firefox, mediaRecorder.mimeType is an empty string and yet the Blob is still created successfully apparently. In chrome, mediaRecorder.mimeType is "video/webm" even though I specified video:false in the getUserMedia options. What's going on here?
  • Do I need to use fetch to convert the blob into an array buffer? It's not hard, but seems a bit hacky.
  • Is there a workaround so it works in Chrome while the codec bug is sorted out? I tried new MediaRecorder(stream, {mimeType:"audio/wav"}); after reading this, but it gave me a "mimeType not supported" error. In fact, any mimeType other than "video/webm" gives an error on chrome, and it seems like firefox is just ignoring the mimeType option.
  • In the mdn article on MediaRecorder they use new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });. Why did they choose that type and codec? How do thay know that's the actual mime type and codec that was used by MediaRecorder? How do they know that mime-type will work in all browsers?

This is a related question/answer. Really, I'd just like some code that I know wont break in 3 months time as things are implemented by browsers and the spec is tweaked. It's be a bonus if it could work with chrome right now too. Thanks!

来源:https://stackoverflow.com/questions/42901470/mediarecorder-api-simple-example-hello-world

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!