How to Play YouTube Video in Android Using YouTube API? - GeeksforGeeks

30 Apr, 2021
YouTube Android Player API lets you play any YouTube video or playlist inside your app that too without leaving your app. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using both Java and Kotlin language.
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin/Java as the programming language
Step 2: Add YouTube Player Android API
Add YouTube Android player API by downloading from here. After downloading extract the file and copy it to the libs folder of the android project.
 Project -> app -> libs
Step 3: Add to gradle Dependency
Add following code to build.gradle(app) and then click sync now
   implementation files(‘libs\\YouTubeAndroidPlayerApi.jar’)
Step 4. Add API Key to play YouTube Video
Add API key by visiting this link. Creates a new project or choose the existing one and create API Key and save somewhere. We will later use it in our code.
Step 5: Add internet permission
Go to AndroidManifest.xml and add the Internet permission. We will need it in order to play a video in our app.
    <uses-permission android:name=”android.permission.INTERNET”/>
Step 6: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.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=".MainActivity">     <com.google.android.youtube.player.YouTubePlayerView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/ytPlayer"        app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
Step 7: 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
Kotlin
import android.os.Bundle;import android.widget.Toast;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import com.google.android.youtube.player.YouTubeInitializationResult;import com.google.android.youtube.player.YouTubePlayer;import com.google.android.youtube.player.YouTubePlayerView; public class MainActivity extends AppCompatActivity {     String api_key = "Enter your API key here";     @Override    protected void    onCreate(@Nullable Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);         // Get reference to the view of Video player        YouTubePlayerView ytPlayer = (YouTubePlayerView)findViewById(R.id.ytPlayer);         ytPlayer.initialize(            api_key,            new YouTubePlayer.OnInitializedListener() {                // Implement two methods by clicking on red                // error bulb inside onInitializationSuccess                // method add the video link or the playlist                // link that you want to play In here we                // also handle the play and pause                // functionality                @Override                public void onInitializationSuccess(                    YouTubePlayer.Provider provider,                    YouTubePlayer youTubePlayer, boolean b)                {                    youTubePlayer.loadVideo("HzeK7g8cD0Y");                    youTubePlayer.play();                }                 // Inside onInitializationFailure                // implement the failure functionality                // Here we will show toast                @Override                public void onInitializationFailure(YouTubePlayer.Provider provider,                                                    YouTubeInitializationResult                                                    youTubeInitializationResult)                {                    Toast.makeText(getApplicationContext(), "Video player Failed", Toast.LENGTH_SHORT).show();                }            });    }}
import android.os.Bundleimport android.widget.Toastimport com.google.android.youtube.player.YouTubeBaseActivityimport com.google.android.youtube.player.YouTubeInitializationResultimport com.google.android.youtube.player.YouTubePlayerimport com.google.android.youtube.player.YouTubePlayerView class MainActivity : YouTubeBaseActivity() {       // Change the AppCompactActivity to YouTubeBaseActivity()         // Add the api key that you had    // copied from google API    // This is a dummy api key    val api_key =  "Enter your API key here"     override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)         // Get reference to the view of Video player        val ytPlayer = findViewById<YouTubePlayerView>(R.id.ytPlayer)         ytPlayer.initialize(api_key, object : YouTubePlayer.OnInitializedListener{            // Implement two methods by clicking on red error bulb            // inside onInitializationSuccess method            // add the video link or the            // playlist link that you want to play            // In here we also handle the play and pause functionality            override fun onInitializationSuccess(                    provider: YouTubePlayer.Provider?,                    player: YouTubePlayer?,                    p2: Boolean            ) {                player?.loadVideo("HzeK7g8cD0Y")                player?.play()            }             // Inside onInitializationFailure            // implement the failure functionality            // Here we will show toast            override fun onInitializationFailure(                    p0: YouTubePlayer.Provider?,                    p1: YouTubeInitializationResult?            ) {               Toast.makeText(this@MainActivity , "Video player Failed" , Toast.LENGTH_SHORT).show()            }        })    }}
Output:
raghav14
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
Services in Android with Example
How to Create and Add Data to SQLite Database in Android?
Content Providers in Android with Example
Android RecyclerView in Kotlin
Services in Android with Example
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Android UI Layouts