聊聊新的 Media API Media Capabilities

关于我们探测是否浏览器能够支持某种视频的播放,我们经常用的 MediaSource.isTypeSupported() 或者 HTMLMediaElement.canPlayType()

来判断,详情可以参看 《探测浏览器对 video 和 audio 的兼容性》 。不过今天介绍一个新的 API , Chrome 在版本 64 开始支持的 navigator.mediaCapabilities;它解决的问题是我们支持了这些格式,但是在当前设备那种格式表现最好呢?

Media Capabilitieswicg 组的草案中明确描述了:

This specification intends to provide APIs to allow websites to make an optimal decision when picking media content for the user. The APIs will expose information about the decoding and encoding capabilities for a given format but also output capabilities to find the best match based on the device’s display.

这个 API 的目标是让浏览器根据提供的视频格式和编码信息,以及比特率等信息择优播放。

how to use

我们先来看看如何使用吧;

const mediaConfig = {
  type: 'media-source', // or 'file'
  audio: {
    contentType: 'audio/webm; codecs=opus',
    channels: '2', // 音轨使用的通道
    bitrate: 132266, // 比特率
    samplerate: 48000 // 采样率
  },
  video: {
    contentType: 'video/webm; codecs="vp09.00.10.08"',
    width: 1920,
    height: 1080,
    bitrate: 2646242, // 比特率
    framerate: '25' // 帧率
  }
};

navigator.mediaCapabilities.decodingInfo(mediaConfig).then(result => {
  console.log('This configuration is' +
      (result.supported ? '' : ' NOT') + ' supported,' +
      (result.smooth ? '' : ' NOT') + ' smooth and' +
      (result.powerEfficient ? '' : ' NOT') + ' power efficient.');
});

其中上面提供了一些基本信息,其中比较关键的是 contentType, bitrate 字段。

你可以提供一系列的视频信息,直到我们可以看见返回
result.smooth 或者 result.powerEfficient
为 true ,及是当前设备能哥提供最好播放体验的选项。

当然目前这个 API 在浏览器的支持程度并不是那么友好:

因此目前还不建议在生产环境使用!我们还是老老实实用 canPlayType 吧。

扩展阅读