我正在尝试在 Opera 12.16(目前最新版本)和 I noticed it doesn't work with mp3
files 中播放 audio
元素但它适用于 ogg
的。
这是我目前仅使用 mp3 文件而不适用于 Opera 的 fiddle : http://jsfiddle.net/hMnsd/1/
解决方案似乎做了这样的事情(如 w3c website 中所指出):
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>
我现在正在使用这个函数来生成声音:
function notificationSound(){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', "http://"+ document.domain +"/files/notification2.mp3");
audioElement.setAttribute('type', 'audio/mpeg');
audioElement.setAttribute('autoplay', 'autoplay');
//audioElement.load()
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
}
为了添加 ogg
文件,我尝试生成所需的结构但没有成功:
var audioElement = document.createElement('audio');
var audioSource1 = document.createElement('source');
var audioSource2 = document.createElement('source');
//mp3 file
audioSource1.setAttribute('src', "http://"+ document.domain +"/files/notification2.mp3");
audioSource1.setAttribute('type', 'audio/mpeg');
//ogg file
audioSource2.setAttribute('src', "http://"+ document.domain +"/files/notification2.ogg");
audioSource2.setAttribute('type', 'audio/ogg');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.append(audioSource2); //opera
audioElement.append(audioSource1);
//audioElement.load()
$.get();
audioElement.addEventListener("load", function() {
audioElement.get(0).play();
}, true);
如何才能让它在 Opera 中与 ogg
文件一起工作?
最佳答案
使用特征检测而不是浏览器检测:
function isMpeg()
{
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
}
function isOgg()
{
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));
}
function isAAC()
{
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''));
}
alert(isMpeg());
alert(isOgg());
alert(isAAC());
示例:http://jsfiddle.net/Cy9AT/1/
另见:http://diveintohtml5.info/everything.html
或使用Modernizer
关于javascript - Opera 中的声音通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17791602/