Reputation: 1300
I have some code that i made to get the current time and duration however both times appear to be wrong, the duration is longer than the regular video and the current time seems to be too fast, it also never reaches the total duration amount and stops slightly before.
The code:
<script type="text/javascript">
var tag = document.createElement('script');
tag.id = 'iframe-demo';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady(event) {
player = new YT.Player('existing-iframe-example', {
events: { // Setup the events to use
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
function onPlayerReady(event) {
event.target.playVideo(); // Auto play the video when ready
}
var myTimer;
function onPlayerStateChange(event){
if(event.data==1) { // playing
myTimer = setInterval(function(){
document.getElementById("time").innerHTML = (player.getCurrentTime() / 60.0000).toFixed(2);
document.getElementById("duration").innerHTML = (player.getDuration() / 60.0000).toFixed(2);
}, 100); // 100 means repeat in 100 ms
}
else { // not playing
clearInterval(myTimer);
}
}
}
</script>
How can this be fixed?
Upvotes: 1
Views: 775
Reputation: 7674
Looking at / 60.0000
I suppose you want to find how much minutes have been passed .The problem with your implementation is that toFixed
is rounding off every time because getCurrentTime()
returns a value having fractional part more that 5 most of the time its like x.9xxxx to fix try Math.floor()
and calculate minutes and seconds separately
Here is something you can use to show min : sec
myTimer = setInterval(function(){
var currentTime = player.getCurrentTime();
var minutes = Math.floor(currentTime / 60) < 10 ? '0' + Math.floor(currentTime / 60.000) : Math.floor(currentTime / 60.000);
var seconds = Math.floor(currentTime % 60) < 10 ? '0' + Math.floor(currentTime % 60.000) : Math.floor(currentTime % 60.000);
document.getElementById("time").innerText = minutes + ' min : '+ seconds+ ' sec';
}, 100); // 100 means repeat in 100 ms
You should note that 100 sec in decimal notation would be 1.40 (1 min 40 sec) but in actual decimal representation it would be 1.66 because in true dec. representation 59 won't wrap up to 1.00 on +1 but only after 99.If you need actual dec. representation change this part
document.getElementById("time").innerText = minutes + ' min : '+ seconds+ ' sec';
to
document.getElementById("time").innerText = minutes + ' min : '+( (seconds/60)*100) + ' sec';
In earlier snippet
Upvotes: 1