Search code examples
androidandroid-youtube-api

How to get the current minute for playing YouTube video in Android


I have the YouTube player embedded in my Android application. I want to get the current minute of the video playing once I press the device's back button. I tried doing this:

  @Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

    Log.d(TAG , "onInitializationSuccess(Provider, YouTubePlayer, boolean ) - Ini ");

    if(!b) {
        youTubePlayer.cueVideo(getIntent().getStringExtra("VIDEO_ID"));
        int minute  = youTubePlayer.getCurrentTimeMillis();

    }

    Log.d(TAG , "onInitializationSuccess(Provider, YouTubePlayer, boolean ) - Fi ");

}

but without success; the minute is always 0. I don't know why.

Any help?


Solution

  • if the video is playing, you can get the current millis using this

    long millis = youTubePlayer.getCurrentTimeMillis();
    

    and just convert it to minutes & seconds. The best i've found so far for conversion is using this code

    long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
    

    Reference: https://stackoverflow.com/a/17625247/5870896