使用JavaScript检测支持的音频格式

在流媒体时代,检测设备和浏览器对音频及视频的支持至关重要。本文介绍了如何使用JavaScript检测给定音频格式是否被支持,以确保媒体内容能在不同设备上顺利播放。通过创建一个类似于检测视频支持的函数,可以轻松实现音频检测,从而提供更好压缩和更快加载速度的媒体内容。
摘要由CSDN通过智能技术生成

As streaming becomes our main entertainment source and vendors fight to create the best video format, it's going to be more and more important that we detect device and browser video support before posting videos on our websites.  We think less about audio but the same principle applies:  detect whether or not a given audio format is supported before using it.  So how do we detect if a given audio type is supported?

随着流媒体成为我们的主要娱乐来源,并且供应商正在努力创造最佳的视频格式,在我们将视频发布到我们的网站之前, 检测设备和浏览器视频支持将变得越来越重要。 我们对音频的考虑较少,但适用相同的原理:在使用给定音频格式之前,先检查是否支持该格式。 那么,如何检测给定的音频类型是否受支持?

We can detect audio format support with HTMLAudioElement.prototype.canPlayType, the same strategy that's used with video:

我们可以使用HTMLAudioElement.prototype.canPlayType来检测音频格式支持,该策略与视频使用的策略相同:


// Create an audio element so we can use the canPlayType method
const audio = document.createElement('audio');

// Does the device support mp3?
audio.canPlayType('audio/mpeg'); // "probably"


There are three possible results from canPlayType:

canPlayType有三种可能的结果:

  • "probably" : The media type appears to be playable

    "probably" :媒体类型似乎可播放

  • "maybe": Cannot tell if the media type is playable without playing it

    "maybe" :如果不播放媒体类型,则无法判断它是否可播放

  • "": The media type is not playable

    "" :媒体类型不可播放

We can create a function much like my supportsVideoType function to make audio detection easy:

我们可以创建一个类似于我的supportsVideoType函数的函数来简化音频检测:


function supportsAudioType(type) {
  let audio;

  // Allow user to create shortcuts, i.e. just "mp3"
  let formats = {
    mp3: 'audio/mpeg',
    mp4: 'audio/mp4',
    aif: 'audio/x-aiff'
  };

  if(!audio) {
    audio = document.createElement('audio')
  }

  return audio.canPlayType(formats[type] || type);
}

// Usage
if(supportsVideoType('mp3') === "probably") {
  // Set the video to mp3
}
else {
  // Set the video to wav or other format
}


Taking the time to detect edge audio and video formats is well worth it, allowing you to deliver clearer media with better compression to improve load time.  Keep these JavaScript functions in mind for your large or small media site!

花时间检测边缘音频和视频格式是非常值得的,它使您可以提供更清晰的媒体并进行更好的压缩以缩短加载时间。 在大型或小型媒体网站上都请牢记这些JavaScript函数!

翻译自: https://davidwalsh.name/detect-supported-audio-formats-javascript

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值