如何在YouTube播放器api中以秒为单位获得准确的总视频时间?

时间:2018-05-16 12:12:32

标签: android youtube

目前我在我的Android应用程序中使用Youtube播放器Api。经过我的全面研究后,我发布了这个问题,因为我无法找到任何正确的解决方案。如何在youtube播放器api中获得总观看时间?

public class YoutubeVideoPlayer extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
private YouTubePlayerView youTubeView;
private String videoCode = "";
private YouTubePlayer youtubePlayer;
private Singleton singleton;


@Override
public void onSaveInstanceState(Bundle outState) {
    if (youtubePlayer != null) {
        youtubePlayer.release();
    }
    youtubePlayer = null;
    super.onSaveInstanceState(outState);
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.youtube_activity_main);
    singleton = Singleton.getReferenceProvider(YoutubeVideoPlayer.this);
    youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);

}


@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    youTubeView.initialize(com.chalklit.classes.Config.DEVELOPER_KEY, this);
    try {
        youtubePlayer.play();
    } catch (Exception e) {

    }
}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
    String url = "https://www.youtube.com/watch?v=" + videoCode;
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
    this.finish();
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    if (youtubePlayer != null) {
        youtubePlayer.release();
        youtubePlayer = null;
    }
    super.onDestroy();
}


@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
    youtubePlayer = player;
    player.setPlayerStateChangeListener(playerStateChangeListener);
    player.setPlaybackEventListener(playbackEventListener);
    if (!wasRestored) {
        player.loadVideo(videoCode);
    } else {

    }
}


private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {

    @Override
    public void onBuffering(boolean arg0) {
        Log.d("Youtube", "onBuffering");
    }

    @Override
    public void onPaused() {
        Log.d("Youtube", "onPaused");
    }

    @Override
    public void onPlaying() {
        Log.d("Youtube", "onPlaying");


    }

    @Override
    public void onSeekTo(int arg0) {

    }

    @Override
    public void onStopped() {
    }

};

private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {

    @Override
    public void onAdStarted() {
    }

    @Override
    public void onError(ErrorReason arg0) {


    }

    @Override
    public void onLoaded(String arg0) {
        Log.d("Youtube", "onLoaded");

    }

    @Override
    public void onLoading() {
        Log.d("Youtube", "onLoading");

    }

    @Override
    public void onVideoEnded() {

    }

    @Override
    public void onVideoStarted() {
    }
};

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RECOVERY_DIALOG_REQUEST) {
        getYouTubePlayerProvider().initialize(com.chalklit.classes.Config.DEVELOPER_KEY, this);
    }
}

private YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerView) findViewById(R.id.youtube_view);
}




@Override
public void onTrimMemory(int i) {
    super.onTrimMemory(i);

}

@Override
protected void onPause() {
    super.onPause();
}


@Override
public void onBackPressed() {
    // TODO Auto-generated method stub

    super.onBackPressed();
}



}

是否可以通过任何方式查看视频的总观看时间? 我无法为此获得任何解决方案。如果您有任何想法,我们如何实现所需的输出将对我有很大的帮助。

3 个答案:

答案 0 :(得分:1)

试试此代码!

public Timer timer = new Timer();

@Override
public void onVideoStarted()
{
    lin_time.setVisibility(View.VISIBLE);
    GlobalApp.Log("YoutubePlayer_","onVideoStarted");
    try
    {
        timer.scheduleAtFixedRate(new MainTask(), 0, 1000);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    img_play.setImageResource(R.drawable.ic_pause_);
    videoEnd = false;
}

public class MainTask extends TimerTask
{
    public void run()
    {
        if (YPlayer != null)
        {
            final int progress = (YPlayer.getCurrentTimeMillis() * 100) / YPlayer.getDurationMillis();
            //handler.sendEmptyMessage(0);
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    if(YPlayer != null)
                    {
                        txt_player_endtime.setText(getDuration(YPlayer.getDurationMillis()));
                        txt_player_starttime.setText(getDuration(YPlayer.getCurrentTimeMillis()));
                        playerSeekbar.setProgress(progress);
                    }
                }
            });
        }
    }
}
public String getDuration(long milliseconds)
{
    long sec = (milliseconds / 1000) % 60;
    long min = (milliseconds / (60 * 1000)) % 60;
    long hour = milliseconds / (60 * 60 * 1000);

    String s = (sec < 10) ? "0" + sec : "" + sec;
    String m = (min < 10) ? "0" + min : "" + min;
    String h = "" + hour;
    String time = "";

    if (hour > 0)
    {
        time = h + ":" + m + ":" + s;
    }
    else
    {
        time = m + ":" + s;
    }
    return time;
}

public int progressToTimer(int progress, int totalDuration)
{
    int currentDuration = 0;
    totalDuration = (int) (totalDuration / 1000);
    currentDuration = (int) ((((double) progress) / 100) * totalDuration);
    // return current duration in milliseconds
    return currentDuration * 1000;
}

答案 1 :(得分:0)

看起来你不能。 YouTube播放器API存在很多限制和问题,因此我构建了开源替代播放器库:Android-YouTube-Player

您尝试做的事情对Android-YouTube-Player来说非常微不足道,只需初始化播放器并添加YouTubePlayerListener即可。通过覆盖方法onCurrentSecond(float second),每当视频的“当前时间”发生变化时,您都会收到通知:

youTubePlayerView.initialize(new YouTubePlayerInitListener() {
    @Override
    public void onInitSuccess(final YouTubePlayer initializedYouTubePlayer) {    
        initializedYouTubePlayer.addListener(new AbstractYouTubePlayerListener() {
            @Override
            public void onReady() {
                String videoId = "6JYIGclVQdw";
                initializedYouTubePlayer.loadVideo(videoId, 0);
            }

            @Override
            public void onCurrentSecond(float seconds) {
                System.out.println("current time: " +seconds);
            }
        });        
    }
}, true);

答案 2 :(得分:0)

public class StopWatch {

    private long startTime = 0;
    private long stopTime = 0;
    private long elapsedTime = 0;
    private boolean running = false;


    public void resume() {
        if(!running) {
            this.startTime = System.currentTimeMillis();
            this.running = true;
        }
    }


    public void pause() {
        if(running) {
            this.stopTime = System.currentTimeMillis();
            this.running = false;
            elapsedTime += stopTime - startTime;
        }
    }


    // elaspsed time in milliseconds
    public long getElapsedTime() {
        if (running) {
            return  elapsedTime + System.currentTimeMillis() - startTime;
        }
        return elapsedTime;
    }


    // elaspsed time in seconds
    public long getElapsedTimeSecs() {
        if (running) {
            return ((System.currentTimeMillis() - startTime + elapsedTime)  / 1000);
        }
        return (elapsedTime / 1000);
    }


}

使用秒表在playbackEventListener中记录经过的时间。

StopWatch stopWatch = new StopWatch();

private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener()    {

    @Override
    public void onBuffering(boolean arg0) {
        stopWatch.pause();
    }

    @Override
    public void onPaused() {
        stopWatch.pause();
    }

    @Override
    public void onPlaying() {
        stopWatch.resume();
    }

    @Override
    public void onSeekTo(int arg0) {

    }

    @Override
    public void onStopped() {
        stopWatch.pause();
    }

};

并将听众设置为播放器

youTubePlayer.setPlaybackEventListener(playbackEventListener);

您可以从stopWatch.getElapsedTimeSecs()

获取经过时间