我刚刚开始学习HTML5,并使用JQuery浏览HTML5音频播放器。我用播放列表编写了一个播放器,一切正常,除了持续时间,我的输入范围滑块不起作用。当我调试时,我发现我的持续时间显示为NAN。我正在设置歌曲初始化后的持续时间。
这是我的JS代码
jQuery(document).ready(function() {
container = $('.container');
playList = $('#playlist');
playListSong = $('#playlist li');
cover = $('.cover');
play = $('#play');
pause = $('#pause');
mute = $('#mute');
muted = $('#muted');
close = $('#close');
song = new Audio('music/Whistle-Flo-Rida-Mp3-Download.mp3','music/Whistle-Flo-Rida-Mp3-Download.mp3');
var canPlay = song.canPlayType('audio/mpeg;');
if (canPlay) {
song.type= 'audio/mpeg';
song.src= 'music/Whistle-Flo-Rida-Mp3-Download.mp3';
}
playListSong.click(function(){
$('#close').trigger('click');
window["song"] = new Audio('music/'+$(this).html()+'.mp3','music/'+$(this).html()+'.mp3');
$('#play').trigger('click');
});
play.live('click', function(e) {
e.preventDefault();
song.play();
//cover.attr("title", song.duration);
$(this).replaceWith('<a class="button gradient" id="pause" href="" title=""><span>k</span></a>');
$('#close').fadeIn(300);
$('#seek').attr('max',song.duration);
});
pause.live('click', function(e) {
e.preventDefault();
song.pause();
$(this).replaceWith('<a class="button gradient" id="play" href="" title=""><span>d</span></a>');
});
mute.live('click', function(e) {
e.preventDefault();
song.volume = 0;
$(this).replaceWith('<a class="button gradient" id="muted" href="" title=""><span>o</span></a>');
});
muted.live('click', function(e) {
e.preventDefault();
song.volume = 1;
$(this).replaceWith('<a class="button gradient" id="mute" href="" title=""><span>o</span></a>');
});
$('#close').click(function(e) {
e.preventDefault();
container.removeClass('containerLarge');
cover.removeClass('coverLarge');
song.pause();
song.currentTime = 0;
$('#pause').replaceWith('<a class="button gradient" id="play" href="" title=""><span>d</span></a>');
$('#close').fadeOut(300);
});
$("#seek").bind("change", function() {
song.currentTime = $(this).val();
$("#seek").attr("max", song.duration);
});
song.addEventListener('timeupdate',function (){
curtime = parseInt(song.currentTime, 10);
$("#seek").attr("value", curtime);
});
});
当我点击播放列表歌曲时,持续时间总是为NAN但默认情况下我设置了一首歌曲,当我点击“播放”按钮时直接在页面加载上然后持续时间正常。它从不适用于播放列表歌曲。
答案 0 :(得分:31)
加载元数据后,使用 loadedmetadata 事件侦听器获取音频的持续时间。执行以下代码:
var audio = new Audio();
audio.src = "mp3/song.mp3";
audio.addEventListener('loadedmetadata', function() {
console.log("Playing " + audio.src + ", for: " + audio.duration + "seconds.");
audio.play();
});