如果您可以访问 mime 类型,您可以简单地使用audio
orvideo
的canPlayType()
方法:
canPlay = (function(){
var a = document.createElement('audio'),
v = document.createElement('video');
function canPlayAudio(type){
var mime = 'audio/';
if (a && a.canPlayType) {
if (type.indexOf(mime) === -1) type = mime+type;
return !!a.canPlayType(type) || !!a.canPlayType(type.replace(/^audio\/(x-)?(.+)$/, mime+'x-$2'))
} return false
}
function canPlayVideo(type){
var mime = 'video/';
if (v && v.canPlayType) {
if (type.indexOf(mime) === -1) type = mime+type;
return !!v.canPlayType(type) || !!v.canPlayType(type.replace(/^video\/(x-)?(.+)$/, mime+'x-$2'))
} return false
}
return {
audio: canPlayAudio,
video: canPlayVideo
}
})();
然后您可以执行这样的测试(注意:包括"audio/"
or"video/"
部分是可选的):
canPlay.audio('audio/mpeg') // true
canPlay.audio('m4a') // true
canPlay.audio('wav') // true
canPlay.audio('flac') // false
canPlay.audio('audio/ogg') // true
canPlay.video('video/mpeg') // false
canPlay.video('video/mp4') // true
canPlay.video('m4v') // true
canPlay.video('video/webm') // true
canPlay.video('avi') // false