Android YouTubePlayer - 在特定时间播放活动

时间:2014-04-17 16:49:33

标签: android android-youtube-api

我需要在视频播放50%的长度后做一些动作。

所以我没有看到一些类似“onCertainMills()”的监听器,我看到onVideoEnded()但是当播放视频的当前时间超过长度/ 2时我需要获取事件。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用YoutubePlayer的属性getCurrentTimeMillis()来不断获取时间,使用getDurationMillis()来获取视频的总持续时间。因此,当youtubePlayer.getCurrentTimeMillis()> = youtubePlayer.getDurationMillis()带有asynctask时,您可以设置所需的任务。 代码如下所示:

    player.setPlaylistEventListener(playlistEventListener);
    player.setPlayerStateChangeListener(playerStateChangeListener);
    player.setPlaybackEventListener(playbackEventListener);

    AsyncTask a = new AsyncTask(); //listener for time
    a.execute(player, 2000,this); //player, time, and activity

    if (!wasRestored) {
      playVideoAtSelection();
    }

    setControlsEnabled(true);

答案 1 :(得分:0)

在结束时,我已经上课,对播放视频的某些时间采取行动。 以下是在视频播放一半后做出一些动作的代码:(+ 1秒)希望它对某人有所帮助。

import android.os.Handler;
import android.util.Log;

import com.clipclash.android.entities.Clip;
import com.google.android.youtube.player.YouTubePlayer;

public class YoutubeCounter {

    Clip clip;
    long counter;
    long startCut;
    long endCut;
    long durationGoal;
    private YouTubePlayer youTubePlayer;
    boolean goal = false;
    Handler h;


    Runnable checkGoal = new Runnable() {
        public void run() {
            getProgress();
            if (counter >= durationGoal) {
                // GOAL !!!
                //TODO MAKE SOME ACTION
                goal = true;
                stopSchedule();
            } else {
                startSchedule();
            }
        }
    };

    public YoutubeCounter(Clip clip) {
        this.clip = clip;
        h = new Handler();
    }


    public void setYouTubePlayer(YouTubePlayer youTubePlayer) {
        this.youTubePlayer = youTubePlayer;
    }

    public void play() {
        if (!goal) {
            if (durationGoal == 0) {
                durationGoal = this.youTubePlayer.getDurationMillis() / 2;
            }
            startCut = youTubePlayer.getCurrentTimeMillis();
            startSchedule();
        }
    }

    public void stop() {
        if (!goal) {
            getProgress();
            stopSchedule();
        }
    }

    private void startSchedule() {
        long newSchedule = durationGoal - counter;
        newSchedule = newSchedule + 1000; // just a little bit more - not requires
        h.postDelayed(checkGoal, newSchedule);
    }

    public void stopSchedule() {
        h.removeCallbacks(checkGoal);
    }

    private void getProgress() {
        try {
            endCut = youTubePlayer.getCurrentTimeMillis();
            long cut = endCut - startCut;
            if (cut < 0) {
                cut = 0;
            }
            counter += cut;
        } catch (Exception e) {
        }
    }

    public long getCounter() {
        return counter;
    }
}