Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Implement YoutubePlayerView Library in Android?
Next article icon

How to Implement YoutubePlayerView Library in Android?

Last Updated : 16 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

If you are looking to display YouTube videos inside your app without redirecting your user from your app to YouTube then this library is very helpful for you to use. With the help of this library, you can simply play videos from YouTube with the help of a video id inside your app itself without redirecting your user to YouTube. Now we will see the implementation of this library in our Android App. We are going to implement this project using both Java and Kotlin Programming Language for Android.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Add the JAR File inside the Libs Folder in Android Studio

Download the JAR file from this link. To add this file open your android project in "Project" mode as shown in the below image.

Import External JAR Files in Android Studio

Then go to Your Project Name > app > libs and right-click on it and paste the downloaded JAR files. You may also refer to the below image. 

Note: You may also refer to this article How to Import External JAR Files in Android Studio?

Step 3: Adding Dependency to the build.gradle File

Go to Module build.gradle file and add this dependency.

implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.3'

Now click on the "sync now" option which you will get to see in the top right corner after adding this library. After that, we are ready for integrating the YouTube video player into the app. 

Step 4: Working with the activity_main.xml File

Now change the project tab in the top left corner to Android. After that navigate to the app > res > layout > activity_main.xml. Inside this, we will create a simple button that will redirect to a new activity where we will play our YouTube video. Below is the XML code snippet for the activity_main.xml file.

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <!-- Button which is used to     navigate to video player screen -->     <Button         android:id="@+id/idBtnPlayVideo"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_centerInParent="true"         android:text="Play Youtube Video"         android:textColor="@color/white" /> </RelativeLayout> 

Step 5: Create a New Empty Activity

Now we will create a new activity where we will display our YouTube video player. To create a new activity navigate to the app > java > your app's package name and right-click on it > New > Activity > Empty Activity > Give a name to your activity and select Java/Kotlin as its language. Now your new activity has been created. (Here we have given the activity name as VideoPlayerActivity). 

Step 6: Implement YoutubePlayerView inside the New Activity 

Below is the code for the activity_video_player.xml file.

XML
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".VideoPlayerActivity">      <!-- Youtube Player view which     will play our youtube video -->     <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView         android:id="@+id/videoPlayer"         android:layout_width="match_parent"         android:layout_height="match_parent"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent"         app:showFullScreenButton="false">     </com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView> </androidx.constraintlayout.widget.ConstraintLayout> 

Step 7: Working with the VideoPlayerActivity File

Before working with the VideoPlayerActivity file let's have a look at how to get the video id of any YouTube video. Open YouTube and search for any video which you want to play inside your app. Play that video inside your browser. In the top section of your browser, there will be an address bar where you can get to see the URL for that video. For example, here we have taken the below URL.

https://www.youtube.com/watch?v=vG2PNdI8axo

Inside the above URL, the video ID is present in the extreme left part i.e after the v = sign is your video id. In the above example, the video ID will be 

vG2PNdI8axo 

In this way, we can get the URL for any video. Now go to the VideoPlayerActivity file and refer to the following code. Below is the code for the VideoPlayerActivity file. Comments are added inside the code to understand the code in more detail.

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);             }         });     } } 
Kotlin
import android.os.Bundle import android.view.Window import android.view.WindowManager 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  class VideoPlayerActivity : AppCompatActivity() {      // id of the video which we are playing.     var video_id = "vG2PNdI8axo"      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)          // below two lines are used to set our screen orientation in landscape mode.         requestWindowFeature(Window.FEATURE_NO_TITLE)         window.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.         supportActionBar?.hide()          // declaring variable for youtubePlayer view         val 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.         lifecycle.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(object : AbstractYouTubePlayerListener() {             fun onReady(youTubePlayer: YouTubePlayer) {                 // loading the selected video into the YouTube Player                 youTubePlayer.loadVideo(video_id, 0)             }              fun onStateChange(youTubePlayer: YouTubePlayer, state: PlayerConstants.PlayerState) {                 // this method is called if video has ended,                 super.onStateChange(youTubePlayer, state)             }         })     } } 

Step 8: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.

Java
import android.content.Intent; import android.os.Bundle; 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(v -> {             // we have declared an intent to open new activity.             Intent i = new Intent(MainActivity.this, VideoPlayerActivity.class);             startActivity(i);         });     } } 
Kotlin
import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity  class MainActivity : AppCompatActivity() {          // variable for our button     lateinit var playBtn: Button      override fun onCreate(savedInstanceState: Bundle?) {         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 {             // we have declared an intent to open new activity.             val i = Intent(this, VideoPlayerActivity::class.java)             startActivity(i)         }     } } 

Step 9: Adding Permissions to the AndroidManifest.xml File

In AndroidManifest.xml, one needs to include the below permission, in order to access the internet. Navigate to the app > AndroidManifest.xml file there you have to add the below permissions. 

<!-- For internet usage -->      <uses-permission android:name="android.permission.INTERNET"/>      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Along with this, you will get to see an activity section inside your application tag. Inside that, add your video player's activity screen orientation to landscape mode. 

<!-- Here my activity name was VideoPlayerActivity -->  <activity android:name=".VideoPlayerActivity"      android:screenOrientation="landscape">  </activity>    

Below is the code for the complete AndroidManifest.xml file:

XML
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.gfg.youtubeplayerview">      <!-- For internet usage -->     <uses-permission android:name="android.permission.INTERNET"/>     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>      <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@style/Theme.YoutubePlayerView">                <!-- Here my activity name was VideoPlayerActivity -->         <activity android:name=".VideoPlayerActivity"             android:screenOrientation="landscape">         </activity>                <activity android:name=".MainActivity">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application> </manifest> 

Output: Run the App on a Physical Device

Check out the project on the below GitHub link: https://github.com/ChaitanyaMunje/YoutubePlayerView


Next Article
How to Implement YoutubePlayerView Library in Android?

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Kotlin
  • Android
  • Android-View
Practice Tags :
  • Java

Similar Reads

    Android YoutubePlayerView Library with Kotlin
    Many applications display videos within their application for displaying video content directly from YouTube. For displaying these YouTube videos within android applications we have to integrate YouTube Player View within the android application. In this article, we will take a look at How to Implem
    5 min read
    How to Implement TNImage Library in Android?
    Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android O
    3 min read
    How to Implement ClockAnimationView Library in Android?
    Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android O
    2 min read
    How to Use Universal Image Loader Library in Android?
    UIL (Universal Image Loader) is a similar library to that of Picasso and Glide which performs loading images from any web URL into ImageView of Android. This image loading library has been created to provide a powerful, flexible, and customizable solution to load images in Android from Server. This
    4 min read
    How to Implement a Video Player Inside an AlertDialog in Android?
    Mainly alert dialogues are used to display an important message to the user. It is possible to embed a video player inside it. This allows developers to create dynamic and interactive video-based dialogs that are useful in various use cases. In this article, we will explore the step-by-step process
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences