[英]Play/pause using howler.js with meteor framework
好的,所以我試圖讓用戶單擊一次或兩次gif時播放/暫停。 我目前已將其設置為用戶只能播放一次聲音而不會停止播放的地方。
我正在使用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');
}
;
});
});
};
我正在使用一些類來跟蹤當前的播放狀態:
我創建了一個howlers
對象來存儲store叫實例,從data-gif-id(因此鍵為data-gif-id,值為is叫對象)中鍵入。 如果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();
}
});
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.