尝试下一个代码:
<audio id="main_audio" autoplay="autoplay" preload="auto" loop="loop">
<source src="sounds/bgmusic.mp3" type="audio/mpeg" />
<source src="sounds/bgmusic.ogg" type="audio/ogg" />
<embed id="main_audio_ie8" hidden="true" autostart="true" loop="true" src="sounds/bgmusic.mp3" />
</audio>
<div id="controls" class="controls">
<a id="playpause" class="play">Play/Pause</a>
</div>
<script>
var isPlaying = function(audio) {return !audio.paused;}
var a = document.getElementById('main_audio');
if(!(a.play instanceof Function)){
a = document.getElementById('main_audio_ie8');
isPlaying = function(audio) {return audio.playState==2;}
}
$('#playpause').on('click', function() {
if (isPlaying(a)) {
a.pause();
} else {
a.play();
}
});
</script>
另一种变体(如果系统上存在 WMPlayer.OCX,则代码必须工作;在 Win2K+IE6SP1+WMP7、WinXP+IE6SP1+WMP9、WinXP+IE8+WMP11 上检查):
<audio id="main_audio" autoplay="autoplay" preload="auto" loop="loop" volume="1.0">
<source src="sounds/bgmusic.mp3" type="audio/mpeg" />
<source src="sounds/bgmusic.ogg" type="audio/ogg" />
<object id="main_audio_ie8" classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" style="display:none;">
<param name="URL" value="sounds/bgmusic.mp3" />
<param name="uiMode" value="invisible" />
<param name="autoStart" value="true" />
<param name="volume" value="100" />
<param name="playCount" value="2147483647" /> <!-- (Int32) 2^31-1==2147483647 - maximum allowed count (for 1 second length audio is equals to 68+ years) -->
</object>
</audio>
<div id="controls" class="controls">
<a id="playpause" class="play">Play/Pause</a>
</div>
<script type='text/javascript'>
window.onload=function(){
var isPlaying,a=document.getElementById('main_audio');
if(a.play instanceof Function)isPlaying=function(audio){return !audio.paused;};
else{
a=document.getElementById('main_audio_ie8');
isPlaying=function(audio){return audio.playState==3;};
a.play=function(){this.controls.play();}
a.pause=function(){this.controls.pause();}
}
document.getElementById('playpause').onclick=function() {
if (isPlaying(a)) {
a.pause();
} else {
a.play();
}
};
};
</script>