日期:2014-05-16  浏览次数:20381 次

为什么我不会播放背景音乐
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<bgsound src="88.mp3" loop="3" autostart="true" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<textarea name="text" style= "resize:none;" id="text"></textarea>
</body>
</html>

------解决方案--------------------
写了个方法,可以兼容IE,FF,Chrome,opera,safari。
但firefox需要音频格式是ogg,不支持mp3,所以如果firefox需要播放,需要有ogg的文件。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
 
<body>
<textarea name="text" style= "resize:none;" id="text"></textarea>
<div id="player"></div>
<script type="text/javascript">
/** 音乐播放器
* @param obj     播放器id
* @param file    音频文件 mp3: ogg:
* @param loop    是否循环
*/
function audioplayer(id, file, loop){
    var audioplayer = document.getElementById(id);
    if(audioplayer!=null){
        document.body.removeChild(audioplayer);
    }

    if(typeof(file)!='undefined'){
        if(navigator.userAgent.indexOf("MSIE")>0){    // IE
    
            var player = document.createElement('bgsound');
            player.id = id;
            player.src = file['mp3'];
            player.setAttribute('autostart', 'true');
            if(loop){
                player.setAttribute('loop', 'infinite');
            }
            document.body.appendChild(player);

        }else{    // Other FF Chome Safari Opera

            var player = document.createElement('audio');
            player.id = id;
            player.setAttribute('autoplay','autoplay');
            if(loop){
                player.setAttribute('loop','loop');