将 blob MIME 类型设置为 wav 仍会导致 webM

Bar*_*t S 3 javascript blob

我按照这篇文章(第 6 步的代码)制作了一个录音机,如下所示。制作完成后audioBlob,我调用一个自定义函数来上传 blob。此功能适用于其他文件类型。

我传递{ type: 'audio/wav' }Blob构造函数。生成的文件确实假装是一个波形文件,可以在浏览器中正常播放,但在 iOS 上则不能。我检查了http://checkfiletype.com/并发现该文件实际上是 WebM:

在此处输入图片说明

我如何确保该文件实际上是一个.wav文件?

从那篇文章中编辑的代码:

navigator.mediaDevices.getUserMedia({ audio: true })
  .then(stream => {
    const mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();

    const audioChunks = [];
    mediaRecorder.addEventListener("dataavailable", event => {
      audioChunks.push(event.data);
    });

    mediaRecorder.addEventListener("stop", () => {
      const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });

      // Custom upload function
      uploadFile(audioBlob);
    });

    setTimeout(() => {
      mediaRecorder.stop();
    }, 3000);
  });
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 8

如何确保文件实际上是 .wav 文件?

Quite easy, no browsers (I know of) does support exporting to wav natively. So you can be sure your file is not a wav file.

The type option of the Blob constructor only says the browser how it should set the MIME-type for further needs (e.g when it will send it to a server). But it doesn't actually change the content you passed as the first argument.

So it won't magically transform your webm file to an other format.

Now, you do have some options to change the format to which the MediaRecorder will output its content, but the set of supported formats / codecs is up to the implementations, and I don't think any browser supports anything else than opus, either in a webm container or in an ogg * one (* FF only).

[edit]: Actually Chrome now supports PCM in webm.

Thanks to the isTypeSupported method, you can very well setup your code to use this format if it ever becomes available, but I personally wouldn't grow too much hope on this, and would look somewhere else if it is required to output a wav file...

const mime = ['audio/wav', 'audio/mpeg', 'audio/webm', 'audio/ogg']
  .filter(MediaRecorder.isTypeSupported)[0];
const recorder = new MediaRecorder(stream, {
  mimeType: mime
});
Run Code Online (Sandbox Code Playgroud)