`

JS对不同的浏览器播放音频文件

 
阅读更多

网上找了好多方法,都没有成功,js如果想要完全控制object对象,会提示TypeError: player.controls is undefined错误,是因为需要安装音频播放器插件。无意中灵机一动采用了一种便捷的方法轻松实现了,无需安装插件(ie自带的media player插件),感谢灵感。

 

Code:

<head>

<meta http-equiv="pragma" content="no-cache" />

<meta http-equiv="Cache-Control" content="no-cache, must-revalidate" />

<meta http-equiv="expires" content="0" />

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

</head>

 

<div id="audioDiv" style="display: none;"></div>

  <a href="javascript:void(0);" onclick="startSound();">播放</a>

  <a href="javascript:void(0);" onclick="stopSound();">停止</a>

<script type="text/javascript">

function startSound() {

var mp3snd = "文件路径";

var myaudiohtml = "";

if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) {

myaudiohtml += '<embed src="'+mp3snd+'" type=application/x-mplayer2 width="0" height="0" autostart="1"/>';

} else if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {

myaudiohtml += '<object data="'+mp3snd+'" type="application/x-mplayer2" width="0" height="0">';

myaudiohtml += '<param name="filename" value="'+mp3snd+'">';

myaudiohtml += '<param name="autostart" value="1">';

myaudiohtml += '<param name="playcount" value="infinite">';

myaudiohtml += '</object>';

} else {

myaudiohtml += '<audio src="'+mp3snd+'" autoplay="autoplay" loop="loop">';

myaudiohtml += '<object data="'+mp3snd+'" type="application/x-mplayer2" width="0" height="0">';

myaudiohtml += '<param name="filename" value="'+mp3snd+'">';

myaudiohtml += '<param name="autostart" value="1">';

myaudiohtml += '<embed height="2" width="2" src="'+mp3snd+'" pluginspage="http://www.apple.com/quicktime/download/" type="video/quicktime" controller="false" controls="false" autoplay="true" autostart="true" loop="false"><br>';

myaudiohtml += '</embed></object>';

myaudiohtml += '</audio>';

}

document.getElementById("audioDiv").innerHTML = myaudiohtml;

}

function stopSound() {

document.getElementById("audioDiv").innerHTML = "";

}

</script>

1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics