我自己建立一个小型音频播放器。此播放器包含7个按钮,单击时可将歌曲添加到播放列表,然后您可以按播放开始播放。一切正常,除了这一件特别的事情:我随机播放的音频文件丢失了大约1秒钟,而且非常烦人。
我调试了系统,当我删除当前时间播放的实时可视化时,问题似乎消失了。
我认为这是近似的一个问题,但我不知道如何解决。
这就像它试图达到"当前时间因为它在Math.floor之后丢失了一些值
这是我的代码:
近似+可视化代码:
function infoSong2(){
pippo = Math.floor(audioElement.currentTime);
pluto = Math.floor(prova);
var pippo2 = minutesModafaka(pippo);
var pluto2 = minutesModafaka(pluto);
$("#info").empty();
$("#info").html(pippo2+"/"+pluto2);
}
function minutesModafaka(seconds){
var minutes = Math.floor(seconds / 60) % 60;
var seconds_left = seconds % 60;
var time_formatted = (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds_left < 10 ? "0" + seconds_left : seconds_left);
return time_formatted;
}
音频播放代码:
function playSong(){
if(arraySongs.length == 0)
{
console.log("No songs selected!");
}
else{
clicks++;
console.log("CLICKS PLAY:"+clicks);
if(clicks > 1)
{
pausePlaySong();
}
else{
audioElement.setAttribute('src', 'audio/'+arraySongs[cont]+'.mp3');
var p2 = arraySongs[cont].split('g')[1];
p2 = parseInt(p2);
$.ajax({
cache:false,
type:"GET",
data:{p2:p2},
url:"http://localhost/gpio2.php",
success:function(msg){
console.log("Connessione avvenuta!");
console.log(msg);
}
});
audioElement.currentTime = pause_time;
audioElement.volume = volume;
audioElement.addEventListener('loadeddata', function() {
prova = audioElement.duration;
});
audioElement.addEventListener('timeupdate', function() {
infoSong2();
});
audioElement.addEventListener('canplaythrough', function () {
console.log("Audio load complete!");
audioElement.play();
});
nextSong();
}
}
}
function nextSong (){
if (cont < arraySongs.length) {
audioElement.addEventListener('ended',function(){
cont++;
console.log("ArraySongs[cont]: "+arraySongs[cont]);
if(arraySongs[cont] == undefined)
{
var p5 = arraySongs[cont-1].split('g')[1];
console.log("Playlist complete!");
this.removeEventListener('ended', arguments.callee);
repeatSong();
}else{
var p3 = arraySongs[cont].split('g')[1];
var p4 = arraySongs[cont-1].split('g')[1];
$.ajax({
cache:false,
type:"GET",
data:{p3:p3},
url:"http://localhost/gpio2.php",
success:function(msg){
console.log("Connessione avvenuta! "+p3);
console.log(msg);
}
});
audioElement.setAttribute('src', 'audio/'+arraySongs[cont]+'.mp3');
audioElement.addEventListener('canplaythrough', function () {
audioElement.play();
});
}
})
}
}
function jackInserted(){
$.ajax({
cache:false,
type:"GET",
url:"http://localhost/jack.php",
success:function(msg){
if(msg != 0)
{
audioElement.pause();
}else{
//stuff
}
}
});
}
setInterval(jackInserted,999);// The PHP page send me 1 if the jack is inserted, 0 if not.
function pauseSong(){
audioElement.pause();
pause_time = Math.floor(audioElement.currentTime);
}