簡體   English   中英

如何在點擊時播放聲音?

[英]How to play a sound on click ?

我在javascript中制作的應用有問題。 當我單擊某些東西時,我想播放聲音。 如果再次單擊此按鈕,我希望聲音再次開始。

我的問題是,聲音播放所需的時間比我單擊兩次所需的時間長,每次單擊都不會啟動聲音。

使用我的應用程序創建JSFiddle將花費很長時間,因此我只是想知道是否有人可以使用此JSFiddle解決此問題: http : //jsfiddle.net/jamiehap/jtCA9/12/

基本上我希望能夠繼續單擊“播放”按鈕,聲音將重新開始:)

下面是我在小提琴中使用的代碼:)

     $(document).ready(function () {
          var audioElement = document.createElement('audio');
          audioElement.setAttribute('src', 'http://static1.grsites.com/archive/sounds/quotes/quotes006.mp3');
          audioElement.setAttribute('autoplay:false', 'autoplay');
          //audioElement.load code above. if you take out :false from the code the file will auto play than everythin works the same after that()
          $.get();
          audioElement.addEventListener("load", function () {
              audioElement.play();
          }, true);


          $(document).keypress(function (e) {
              if (e.which == 13) { //press enter the audio will play
                  audioElement.play();

              } else if (e.which == 32) { //press spacebar the audio will                             pause play
                  audioElement.pause();
              }
          });

// the code below wil allow you to click the play and stop button with the mouse
          $('.play-button').click(function () { 
              audioElement.play();
          });


          $('.pause').click(function () {
              audioElement.pause();
          });
      });

調用播放前,將當前時間設置為零

$('.play-button').click(function () {
    audioElement.pause();
    audioElement.currentTime = 0;
    audioElement.play();
});

播放前重新加載音頻文件:

$('.play-button').click(function () {
audioElement.load();
audioElement.play();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM