2015-06-19 60 views
0

好吧,所以我試圖讓用戶在點擊GIF一次或兩次時播放/暫停。我現在已經設置了用戶只能在不停止播放的情況下播放聲音的地方。使用流星框架的howler.js播放/暫停

我正在使用JavaScript音頻庫howler.js和流星框架。

下面是代碼:

Template.gif.rendered = function() { 
    freezeframe_options = { 
    trigger_event: "click" 
}; 

$.getScript("/client/scripts/freezeframe.js", function() { 
    $(".gif").click(function() { 
     if (!$(this).hasClass('played')) { 
      var gifId = $(this).attr("data-gif-id"); // Will return the gif ID number 
      var soundFile = $(this).attr("data-sound-file"); // Will return the sound file 

      var fileFormat = "mp3"; 
      var mp3Test = new Audio(); 
      var canPlayMP3 = (typeof mp3Test.canPlayType === "function" && mp3Test.canPlayType("audio/mpeg") !== ""); 
      if (!canPlayMP3) { 
       fileFormat = "ogg"; 
      } 

      var sound = new Howl({ 
       urls: ['sounds/' + soundFile + '.' + fileFormat] 
      }).play(); 

      $(this).addClass('played'); 
     } 
     ; 
    }); 
    }); 

}; 

回答

0

我使用了幾類來跟蹤當前的播放狀態:

  • 播放=聲音當前正在播放
  • 暫停=的聲音目前已暫停
  • 播放=聲音已完整收聽至少一次

我已經創建了一個howlers對象來存儲Howl實例,鍵入data-gif-id(因此key是data-gif-id,值是Howl對象)。如果data-gif-id鍵不在howlers對象中,那麼我會創建一個新的Howl對象,否則,我只是在已經在howlers對象中的相應值上調用play()pause()方法。

下面是代碼:

Template.gif.rendered = function() { 
    freezeframe_options = { 
    trigger_event: "click" 
    }; 

    howlers = {}; // set up an object to hold the Howl instances 

    // moved these static lines out of the click function 
    var fileFormat = "mp3"; 
    var mp3Test = new Audio(); 
    var canPlayMP3 = (typeof mp3Test.canPlayType === "function" && mp3Test.canPlayType("audio/mpeg") !== ""); 
    if (!canPlayMP3) { 
    fileFormat = "ogg"; 
    } 

    $.getScript("/client/scripts/freezeframe.js", function() { 
    $(".gif").click(function() { 
     var e = $(this); 
     var soundFile = e.attr("data-sound-file") + '.' + fileFormat; // Will return the sound file 
     var gifId = e.attr("data-gif-id"); // Will return the gif ID number 
     if (gifId in howlers){ 
     if (e.hasClass('paused')){ // If currently paused, unpause 
      e.removeClass('paused'); 
      e.addClass('playing'); 
      howlers[gifId].play(); 
     } else if (e.hasClass('playing')) { // If currently playing, pause 
      e.removeClass('playing'); 
      e.addClass('paused'); 
      howlers[gifId].pause(); 
     } else { // If not playing and not paused, play 
      e.addClass('playing'); 
      howlers[gifId].play(); 
     } 
     } else { // this is a new instance, so add it to the howlers object and start playing 
     howlers[gifId] = new Howl({ 
      urls: ['sounds/' + soundFile], 
      onend: function(){ // when playing ends, add the 'played' class to track which sounds have been played completely 
      e.removeClass('playing'); 
      e.addClass('played'); 
      } 
     }); 
     e.addClass('playing'); 
     howlers[gifId].play(); 
     } 
    }); 
    }); 

}; 
+0

太感謝你了!我一直試圖找到一種方法來合併它,你精確地解決了它 謝謝! –