How to play multiple videos in YouTube Player API?

别来无恙 提交于 2020-01-14 06:35:20

问题


I am trying to play a number of videos from YouTube using the YouTube Player API in Android Studio. I have the Video Id of each videos in different strings with name of video titles. Now I want the player to play video when each button with video title is clicked.

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
        player.cueVideo("my_video_id_1");
    }
}

Using this method, I don't know how to 'change the string name' when second button is clicked to play the second video in the same player.

Any answers are highly appreciated!


回答1:


First, declare an YouTubePlayer instance and initialize your YouTubePlayerView at onCreate.

private YouTubePlayer youTubePlayer;


@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
      if(youTubePlayer == null){
        youTubePlayer = player;
      }
    }
}

Now, provide the video Id corresponding to each button listener.

    switch (btnId) {
        case R.id.btnOne:
            playVideo("my_video_id_1");
            break;
        case R.id.btnTwo:
            playVideo("my_video_id_2");
            break;
        case R.id.btnThree:
            playVideo("my_video_id_3");
            break;

        default:
            break;
    }

Finally, play the video

private void playVideo(String videoId){
    if(youTubePlayer != null){
        youTubePlayer.loadVideo(videoId);
    }
}


来源:https://stackoverflow.com/questions/43044146/how-to-play-multiple-videos-in-youtube-player-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!