📜  如何在Android中实现YoutubePlayerView库?

📅  最后修改于: 2021-05-10 13:56:50             🧑  作者: Mango

如果您希望在应用程序内显示YouTube视频而不将用户从应用程序重定向到YouTube,则该库对您的使用非常有帮助。借助该库,您可以简单地借助应用本身内部的视频ID来播放YouTube中的视频,而无需将用户重定向到YouTube。现在,我们将在Android App中看到该库的实现。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在Android Studio的libs文件夹内添加jar文件

从此处的链接下载jar文件。要添加此文件,请在“ Project ”模式下打开您的android项目,如下图所示。

在Android Studio中导入外部JAR文件

然后转到您的项目名称>应用程序>库,然后右键单击它并粘贴下载的JAR文件。您也可以参考下图。

步骤3:现在在您的build.gradle文件中添加依赖项

要添加此依赖项。导航到应用程序的名称> app>,您将看到build.gradle文件。在该文件内,将依赖项添加到“依赖项”部分。

现在,单击立即同步”选项,添加该库后,您将在右上角看到该选项。之后,我们准备将YouTube视频播放器集成到应用中。

步骤4:使用activity_main.xml文件

现在,将左上角的项目标签更改为Android。之后,导航到应用程序> res>布局> activity_main.xml 。在其中,我们将创建一个简单的按钮,该按钮将重定向到一个新的活动,在该活动中我们将播放我们的YouTube视频。以下是activity_main.xml文件的XML代码段。

XML


  
    
    


XML


  
    
    
    
      


Java
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView;
  
public class VideoPlayerActivity extends AppCompatActivity {
    // id of the video 
    // which we are playing.
    String video_id = "vG2PNdI8axo";
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
          
        // below two lines are used to set our 
        // screen orientation in landscape mode.
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                             WindowManager.LayoutParams.FLAG_FULLSCREEN);
  
        setContentView(R.layout.activity_video_player);
          
        // below line of code is 
        // to hide our action bar.
        getSupportActionBar().hide();
          
        // declaring variable for youtubeplayer view
        final YouTubePlayerView youTubePlayerView = findViewById(R.id.videoPlayer);
          
        // below line is to place your youtube player in a full screen mode (i.e landscape mode)
        youTubePlayerView.enterFullScreen();
        youTubePlayerView.toggleFullScreen();
          
        // here we are adding observer to our youtubeplayerview.
        getLifecycle().addObserver(youTubePlayerView);
          
        // below method will provides us the youtube player
        // ui controller such as to play and pause a video 
        // to forward a video
        // and many more features.
        youTubePlayerView.getPlayerUiController();
          
        // below line is to enter full screen mode.
        youTubePlayerView.enterFullScreen();
        youTubePlayerView.toggleFullScreen();
  
        // adding listener for our youtube player view.
        youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
            @Override
            public void onReady(@NonNull YouTubePlayer youTubePlayer) {
                // loading the selected video into the YouTube Player
                youTubePlayer.loadVideo(video_id, 0);
            }
  
            @Override
            public void onStateChange(@NonNull YouTubePlayer youTubePlayer,
                                      @NonNull PlayerConstants.PlayerState state) {
                // this method is called if video has ended,
                super.onStateChange(youTubePlayer, state);
            }
        });
    }
}


Java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
    // variable for our button
    Button playBtn;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // Initialize our Button
        playBtn = findViewById(R.id.idBtnPlayVideo);
          
        // we have set onclick listener for our button
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // we have declared an intent to open new activity.
                Intent i = new Intent(MainActivity.this, VideoPlayerActivity.class);
                startActivity(i);
            }
        });
    }
}


XML


  
    
    
    
  
    
        
        
        
        
        
            
                
  
                
            
        
    
  


步骤5:创建一个新的空活动

现在,我们将创建一个新活动,在其中显示我们的YouTube视频播放器。要创建新活动,请导航至应用程序> Java >应用程序的包名称,然后右键单击它>新建>活动>空活动>为活动命名,并确保其语言为Java 。现在,您的新活动已创建。 (在这里,我们将活动名称命名为VideoPlayerActivity )。

步骤6:在新活动中实现YoutubePlayerView

以下是activity_video_player.xml文件的代码。

XML格式



  
    
    
    
      

步骤7:使用VideoPlayerActivity。 Java文件

在使用VideoPlayerActivity之前。 Java文件,让我们看一下如何获取任何YouTube视频的视频ID。打开YouTube并搜索您想要在应用程序中播放的任何视频。在浏览器中播放该视频。在浏览器的顶部,将有一个地址栏,您可以在其中查看该视频的URL。例如,这里我们采用以下URL。

在上述网址内,视频ID出现在最左端,即在v =符号之后是您的视频ID。在上面的示例中,视频ID为

这样,我们可以获取任何视频的URL。现在转到VideoPlayerActivity。 Java文件并参考以下代码。以下是VideoPlayerActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView;
  
public class VideoPlayerActivity extends AppCompatActivity {
    // id of the video 
    // which we are playing.
    String video_id = "vG2PNdI8axo";
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
          
        // below two lines are used to set our 
        // screen orientation in landscape mode.
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                             WindowManager.LayoutParams.FLAG_FULLSCREEN);
  
        setContentView(R.layout.activity_video_player);
          
        // below line of code is 
        // to hide our action bar.
        getSupportActionBar().hide();
          
        // declaring variable for youtubeplayer view
        final YouTubePlayerView youTubePlayerView = findViewById(R.id.videoPlayer);
          
        // below line is to place your youtube player in a full screen mode (i.e landscape mode)
        youTubePlayerView.enterFullScreen();
        youTubePlayerView.toggleFullScreen();
          
        // here we are adding observer to our youtubeplayerview.
        getLifecycle().addObserver(youTubePlayerView);
          
        // below method will provides us the youtube player
        // ui controller such as to play and pause a video 
        // to forward a video
        // and many more features.
        youTubePlayerView.getPlayerUiController();
          
        // below line is to enter full screen mode.
        youTubePlayerView.enterFullScreen();
        youTubePlayerView.toggleFullScreen();
  
        // adding listener for our youtube player view.
        youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
            @Override
            public void onReady(@NonNull YouTubePlayer youTubePlayer) {
                // loading the selected video into the YouTube Player
                youTubePlayer.loadVideo(video_id, 0);
            }
  
            @Override
            public void onStateChange(@NonNull YouTubePlayer youTubePlayer,
                                      @NonNull PlayerConstants.PlayerState state) {
                // this method is called if video has ended,
                super.onStateChange(youTubePlayer, state);
            }
        });
    }
}

步骤8:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
    // variable for our button
    Button playBtn;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // Initialize our Button
        playBtn = findViewById(R.id.idBtnPlayVideo);
          
        // we have set onclick listener for our button
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // we have declared an intent to open new activity.
                Intent i = new Intent(MainActivity.this, VideoPlayerActivity.class);
                startActivity(i);
            }
        });
    }
}

步骤9:在清单文件中添加Internet权限

导航到app> AndroidManifest.xml文件,您必须在其中添加以下权限。

随之,您将看到应用程序标签内的活动部分,该部分将视频播放器的活动屏幕方向添加到横向模式。

以下是完整的AndroidManifest.xml文件的代码:

XML格式



  
    
    
    
  
    
        
        
        
        
        
            
                
  
                
            
        
    
  

输出:在真实设备上运行应用程序

在下面的GitHub链接上查看项目: https : //github.com/ChaitanyaMunje/YoutubePlayerView

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!