好的,所以我试图让用户在点击gif一次或两次时播放/暂停。我目前已将其设置为用户只能在不停止播放声音的情况下播放一次。
我正在使用javascript音频库howler.js和meteor框架。
以下是代码:
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 :(得分:0)
我使用几个类来跟踪当前的播放状态:
我创建了一个howlers
对象来存储Howl实例,键入了data-gif-id(所以键是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();
}
});
});
};