everyone
I wrote simple music player, but I have one problem. I used ajax to get new source from file php and that works OK, but I have no idea how play new song. Simple audio.play() doesn’t work. I try to repair This is my code:
function timer(){
timeleft = $("span#timeleft");
slider = $("div#slider");
$(audio).bind('timeupdate', function(){
var rem = parseInt(audio.duration - audio.currentTime, 10),
pos = (audio.currentTime / audio.duration) * 315,
mins = Math.floor(rem/60, 10),
secs = rem - mins*60;
timeleft.text('- ' + mins + ':' + (secs > 9 ? secs : '0' + secs));
slider.css({width: pos + 'px'});
});
}
$(document).ready(function(){
audio = $("audio#audio-player-header").get(0);
$("div#controls").click(function(){
$(this).toggleClass("pause");
if(audio.paused){
audio.play();
timer();
}else{
audio.pause();
}
});
audio.addEventListener("ended", function(){
$.post("php/player.php", function(result){
audio.src = result;
});
audio.play(); // here is the problem
timer();
});
});
And HTML:
<div id="player">
<div id="controls" class="play"></div>
<div id="music-title">
<div id="slider">
<div id="wrap-music-title">
<p id="music-title">Jamie T - Chaka Demus</p>
</div>
</div>
</div>
<span id="timeleft"></span>
<div id="player-header">
<audio id="audio-player-header" src="music/rock/Jamie T - Chaka Demus.mp3">
</audio>
</div>
</div>
I found on stackoverflow and web some solutions, but nothing works here. Thanks in advance for any help.
You’ve created a race condition in which you’re calling
audio.play()before your ajax call returns. You could (A)listen for the audiocanplayevent then trigger play or (B)just set theautoplayattribute of your audio tag.Option A:
Option B: