0

这是一个小的 html 文件,它创建一个计时器图像并在我单击它时播放计时器音乐。

<html>
    <head>
        <script language="javascript" type="text/javascript">
            function playSound(soundfile) {
                document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
            }
        </script>
    </head>
    <body>
        <table width="100%" height="100%">
            <tr>
                <td align="center" valign="middle">
                    <a href="#" onclick="playSound('timer.mp3');">
                        <img src="timer.png"/>
                    </a>
                </td>
            </tr>
        </table>
        <span id="dummy"></span>
    </body>
</html>

我是 JavaScript 新手,但这是我想要的:

当用户单击图像时,应不间断地播放音乐,直到用户再次单击图像。

我该怎么做呢?

4

2 回答 2

2
<audio id="player" controls="controls"></audio>     Remove "control" if you don't
<button onClick="playFile('timer.mp3')">Play/Stop</button>            need it.

var playing = false;                                    //pre set plaing to false
function playFile(n){
    var player = document.getElementById("player");     //get the <audio>
    player.src = n;                                     //set the url
    playing = !playing;                                 //flip the status
    playing ? player.play(): player.stop();             //play/stop
    player.addEventListener("ended", function(){        //When ended,
        player.play();                                  //play again
        //do other stuff
    });
}
于 2012-12-12T05:25:10.167 回答
1
 <audio id="myAudio" controls preload loop>
  <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4" type='audio/mp4'>
   <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga" type='audio/ogg; codecs=vorbis'>
    Your user agent does not support the HTML5 Audio element.
   </audio>
     <img src="img/ex1.png" onclick="aud_play_pause()"/>
       <script>
        function aud_play_pause() {
      var myAudio = document.getElementById("myAudio");
      if (myAudio.paused) {
    myAudio.play();
       } else {
      myAudio.pause();
       }
  }
   </script>

使用此代码在图像按钮上不间断地播放音频。在源 src 中设置您的音频。

于 2012-12-12T05:27:31.670 回答