添加事件侦听器,在声音播放完毕后更改/删除类

时间:2015-09-21 08:03:23

标签: javascript jquery audio

如何在声音文件结束时添加一个执行函数来删除类的事件侦听器。 (完成播放后,让Jsfiddle中的播放按钮变回绿色)

jsfiddle:https://jsfiddle.net/wyfjdgyb/4/

$(".play").on('click',function(){
    var key = $(this).attr('key');     
    EvalSound(key);
    var this_play = $(this);
    $(".play").each(function() {
        if ($(this)[0] != this_play[0]) {
            $(this).removeClass("pause");
        }
    });
    $( this ).toggleClass( "pause" );
});

var thissound = new Audio();
var currentKey;
function EvalSound(key) {
    if(currentKey !== key)
        thissound.src = "http://99centbeats.com/beats/" + key + ".mp3";      
    currentKey = key;

    if (thissound.paused)
        thissound.play();
    else
        thissound.pause();
        thissound.currentTime = 0;
        currentPlayer = thissound;     
}
$(".play").bind('ended', function(){
    // done playing
    $(this).removeClass("pause");
});   

2 个答案:

答案 0 :(得分:1)

您可以借助current Time对象的durationaudio属性来实现它。您应该设置一个间隔(在setInterval()函数的帮助下)并使用较低的延迟来检查这两个属性是否相同。当它们变得相同时,意味着音轨到达终点。请记住在需要时清除间隔时间。

var interval;
function EvalSound(key) {

    if(currentKey !== key)
        thissound.src = "http://99centbeats.com/beats/" + key + ".mp3";      
    currentKey = key;

    if (thissound.paused) {
        thissound.play();
        interval = setInterval(function() {
            if(thissound.currentTime == thissound.duration) {
                clearInterval(interval);    
                console.log('Sound played!');
            }           
        },100);
    } else {
        thissound.pause();
        thissound.currentTime = 0;
        currentPlayer = thissound;
        clearInterval(interval);   
    }    
}

这是the fiddle

PS:好节拍,伙计! :)

答案 1 :(得分:1)

您可以将已结束的处理程序附加到声音元素而不是DOM元素,并将单击的元素传递给您的函数。

代码:

 function EvalSound(el, key) {

     thissound.addEventListener('ended', function () {
         // done playing
         $(el).removeClass("pause");
     });

     if (currentKey !== key) thissound.src = "http://99centbeats.com/beats/" + key + ".mp3";
     currentKey = key;

     if (thissound.paused) thissound.play();
     else thissound.pause();
     thissound.currentTime = 0;
     currentPlayer = thissound;

 }

演示:https://jsfiddle.net/9a9jbqzz/