Skip to content
Related Articles

Related Articles

Improve Article

How to Play YouTube Video in Android Using YouTube API?

  • Last Updated : 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 by Step Implementation

Step 1: Create a new project

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

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: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




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();
                }
            });
    }
}

Kotlin




import android.os.Bundle
import android.widget.Toast
import com.google.android.youtube.player.YouTubeBaseActivity
import com.google.android.youtube.player.YouTubeInitializationResult
import com.google.android.youtube.player.YouTubePlayer
import 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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :