javascript 在 html5 音频元素上使用 jquery 绑定“timeupdate”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19739384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:39:45  来源:igfitidea点击:

bind 'timeupdate' with jquery on html5 audio element

javascriptjqueryhtml

提问by user1053263

I'm just trying to update a simple progress bar on time update, so I'm doing this:

我只是想按时间更新更新一个简单的进度条,所以我这样做:

var audioFile = thisPlayerBtn.attr('audioFile');
var audioFilePlayer = document.createElement('audio');
audioFilePlayer.setAttribute('src', audioFile);
audioFilePlayer.setAttribute('id', 'theAudioPlayer');
audioFilePlayer.load();

$.get();

audioFilePlayer.addEventListener("load", function() {
    audioFilePlayer.play();
}, true);       

$('#hiddenAudioElements').append(audioFilePlayer);
audioFilePlayer.play();
audioFilePlayer.bind('timeupdate', updateTime);


var updateTime = function(){
    var thisPlayer = $(this);
    var widthOfProgressBar = Math.floor( (100 / thisPlayer.duration) * thisPlayer.currentTime);
    $('#songIdForPorgessBar').css({
        'width':widthOfProgressBar+'%'
    });
}

Firebug says that "bind" is not a function, so I swapped it with "addEventListener" and I get no error but the progress bar doe not update.

Firebug 说“绑定”不是一个函数,所以我用“addEventListener”交换了它,我没有收到错误,但进度条没有更新。

Not sure what I'm doing wrong or if there's a better way of going about it. Here is my fiddle: http://jsfiddle.net/j44Qu/it works, plays the audio, just doesn't update the progress bar and I'm stumped.

不确定我做错了什么,或者是否有更好的方法来解决它。这是我的小提琴:http: //jsfiddle.net/j44Qu/它可以工作,播放音频,只是不更新​​进度条,我很难过。

回答by Musa

Your problem is that you're using jQuery objects when you should be using dom nodes and vice versa.
bindis a jQuery method yet you call it on the audio node

您的问题是您在应该使用 dom 节点时使用了 jQuery 对象,反之亦然。
bind是一个 jQuery 方法,但您在音频节点上调用它

$(audioFilePlayer).bind('timeupdate', updateTime);

durationand currentTimeare audio node properties but you try to reference them from a jQuery object

duration并且currentTime是音频节点属性,但您尝试从 jQuery 对象中引用它们

var widthOfProgressBar = Math.floor( (100 / this.duration) * this.currentTime);

http://jsfiddle.net/j44Qu/1/

http://jsfiddle.net/j44Qu/1/