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
相关资源:jdk-8u281-windows-x64.exe