Html 如何检测 HTML5 音频 MP3 支持?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8469145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:57:08  来源:igfitidea点击:

How to detect HTML5 audio MP3 support?

htmlhtml5-audiobrowser-feature-detection

提问by footy

I know how to check in Javascript if HTML5 audio playback is available. But how do I specifically check if MP3 audio playback is available, as IE9 and Chrome support it, while Firefox and Opera do not.

如果 HTML5 音频播放可用,我知道如何检查 Javascript。但是我如何专门检查 MP3 音频播放是否可用,因为 IE9 和 Chrome 支持它,而 Firefox 和 Opera 不支持。

回答by keyboardP

You could either check the User-Agent and see what browser is being used or you could test support with Javascript.

您可以检查 User-Agent 并查看正在使用的浏览器,或者您可以使用 Javascript 测试支持。

var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));

I got the above code from this page.

我从这个页面得到了上面的代码。

return !!(a.canPlayType) is better because (some recent versions of)Firefox not supports mp3 and a.canPlayType('audio/mpeg;') will be false

return !!(a.canPlayType) 更好,因为(某些最新版本)Firefox 不支持 mp3 并且 a.canPlayType('audio/mpeg;') 将是假的

回答by Tim

Modernizris a library for feature detection. You can use it to do the work for you.

Modernizr是一个用于特征检测的库。您可以使用它来为您完成工作。

According to the documentation:

根据文档

If audio support is detected, Modernizr assesses which formats the current browser will play. Currently, Modernizr tests ogg, mp3, wav and m4a.

Important: The values of these properties are not true booleans. Instead, Modernizr matches the HTML5 spec in returning a string representing the browser's level of confidence that it can handle that codec. These return values are an empty string (negative response), "maybe" and "probably". The empty string is falsy, in other words: Modernizr.audio.ogg == '' and '' == false

如果检测到音频支持,Modernizr 会评估当前浏览器将播放哪些格式。目前,Modernizr 测试 ogg、mp3、wav 和 m4a。

重要提示:这些属性的值不是真正的布尔值。相反,Modernizr 匹配 HTML5 规范,返回一个字符串,表示浏览器可以处理该编解码器的置信度。这些返回值是一个空字符串(否定响应)、“可能”和“可能”。空字符串是假的,换句话说:Modernizr.audio.ogg == '' and '' == false

回答by Shoaib Iqbal

var test_audio= document.createElement("audio") //try and create sample audio element 
var test_video= document.createElement("video") //try and create sample video element
var mediasupport={audio: (test_audio.play)? true : false, video: (test_video.play)? true :     false}

alert("Audio Element support: " + mediasupport.audio + "\n"
+ "Video Element support: " + mediasupport.video
)