js播放背景音樂

這裏有兩種實現方式,基本上原理差不多:

 <script>
        var isplay = false;
        function playmp3() {
            if (isplay == false) {
                var player = "<embed src=\"/我們說好的.mp3\" hidden=\"true\" autostart=\"true\" loop=\"true\">";
                //“1.mp3”路徑,自己改。loop=-1 循環播放。
                document.getElementById("play").innerHTML += player;
                isplay = true;
            } else {
                document.getElementById("play").innerHTML = "點擊播放";
                isplay = false;
            }
        }
    </script>
<div id="play" οnmοuseοver="this.style.cursor='pointer';" οnclick="playmp3();">點擊播放</div>


另一種實現方式:

    <input type="button" value="立即播放" οnclick="play_click(this, '我們說好的.mp3');">
    <div id="div2"></div>
    <script language="javascript">
        function play_click(sef, url) {
            var div = document.getElementById('div1');
            div.innerHTML = '<embed src="' + url + '" loop="0" autostart="true" hidden="true"></embed>';
            var emb = document.getElementsByTagName('EMBED')[0];
            if (emb) {
                /* 這裏可以寫成一個判斷 wav 文件是否已加載完畢,以下采用setTimeout模擬一下 */
                div = document.getElementById('div2');
                div.innerHTML = 'loading: ' + emb.src;
                sef.disabled = true;
                setTimeout(function () { div.innerHTML = ''; }, 1000);
            }
        }
    </script>
<div id="div1"></div>

近期又發現了一個,試了試也不錯:

 <script>
        var mp3snd = "我們說好的.mp3";
        var bkcolor = "000000";

        if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
            document.write('<bgsound src="' + mp3snd + '" loop="-1">');
        }
        else if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
            document.write('<object data="' + mp3snd + '" type="application/x-mplayer2" width="0" height="0">');
            document.write('<param name="filename" value="' + mp3snd + '">');
            document.write('<param name="autostart" value="1">');
            document.write('<param name="playcount" value="infinite">');
            document.write('</object>');
        }
        else {
            document.write('<audio src="' + mp3snd + '" autoplay="autoplay" loop="loop">');
            document.write('<object data="' + mp3snd + '" type="application/x-mplayer2" width="0" height="0">');
            document.write('<param name="filename" value="' + mp3snd + '">');
            document.write('<param name="autostart" value="1">');
            document.write('<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="true" bgcolor="#' + bkcolor + '"><br>');
            document.write('</embed></object>');
            document.write('</audio>');
        }

    </script>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章