Dave Price
Dave Price

Reputation: 21

YouTube IFrame API stopping before end

Is it possible to stop a video using the YouTube API one second before the end or just stopping it resetting back to the beginning? This is regardless of the length of the video itself.

Thanks in advance

Upvotes: 2

Views: 516

Answers (2)

insaner
insaner

Reputation: 1705

I ran into an issue where for some reason the iframe player was stopping the video before the video's end, and so not triggering the ENDED event, and ran into this question while trying to find a solution for that. Since my approach can solve your problem as stated, here's what I did (I left the console.log() debug lines in to make it easier for someone else using this to play around with):

var player_timeout;
function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
        console.log("PLAY [" + event.data + "]");
        timeout_set();
        }
    if (event.data == YT.PlayerState.PAUSED) {
         console.log("PAUSED [" + event.data + "]");
        clearTimeout(player_timeout);
        }
    }
    
function timeout_func() {
    console.log("timeout_func");
    player.stopVideo(); // or whatever other thing you want to do 1 second before the end of the video
    }
    
function timeout_set() {
     console.log("timeout_set");
    var almostEnd_ms = (player.getDuration() - player.getCurrentTime() - 1) * 1000;
     console.log("almostEnd_ms: " + almostEnd_ms);
     console.log("player.getCurrentTime(): " + player.getCurrentTime());
    player_timeout = setTimeout(timeout_func, almostEnd_ms);
    }

Upvotes: 1

sctskw
sctskw

Reputation: 1598

I disagree with the argument of NOT being able to stop a video before it ends. Specifically, in the API, you have access to:

https://developers.google.com/youtube/js_api_reference#Playback_status

Player.getCurrentTime();
Player.getDuration();

If you were to monitor the player object and compare these two, you could easily stop the video before it ends. An example would be (although probably not good in production):

setInterval(function() {
  var player = getPlayer(); //retrieve the player object

  if(player) {
   var duration = player.getDuration();
   var current  = player.getCurrentTime();


   if((duration - current) <= 1) {
     player.stopVideo();
   }
 }
}, 1000); //every second

Upvotes: 1

Related Questions