YouTube Player API in Android using Kotlin

Introduction:

In this article, we will learn how to integrate and play a video using YouTube API in Android with Kotlin.

YouTube Android Player API enables developers to incorporate or integrate video playback functionality into our own developed Android applications. Using this API, we can load and cue play videos. It has a built in play controls for controlling the video playback actions such as Play, Pause or Seek to a specific time/point in the current video. Our Android Phone must have the YouTube app. Because this API interact with service that is a part of YouTube app.

Before going to coding part, we need to follow below steps for setup the YouTube API in our own developed app

  1. Download YouTube API client library from the following link, basically this library is a jar file. https://developers.google.com/youtube/android/player/downloads/
  2. Register our app in Google API console & Enable YouTube Android Player API in Google API Console. In this way we will obtain an Android API key, which is must for using this API. https://console.developers.google.com/apis/

Register app and get Android API Key:

  1. Open Google API Console.
  2. Create a new project or choose your existing project in API Console.
  3. Open API page and search for YouTube Android Player API.
  4. Then select enable API and go to credentials page.
  5. Then select API Key will creates your API key. We can improve the security of the API key with package name & SHA-1 key of your system.

Step 1 - Creating a new project with Kotlin

  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.

Step 2: Setting up YouTube Library and Manifest:

In this part, we will see how to setup the YouTube API Client library for the project.

  1. With respect to our previous step, we have already downloaded the API client library for YouTube API as a Zip file.
  2. Then extract the jar files and add them to “libs” folder.
  3. Then open app level build.gradle file and add the following lines in dependencies.
    dependencies { 
       …
       implementation files('libs/YouTubeAndroidPlayerApi.jar')   
        …
    }
  4. Then click “Sync Now” to setup your project.
  5. Now the project is ready and add internet permissions in AndroidManifest.xml.
    <uses-permission android:name="android.permission.INTERNET"/>

Step 3: Integration of YouTube Android Player in Screen using Kotlin:

In this step, we will learn how to embed YouTube Android Player & how to play a particular video (by its id).

  1. Open your layout file and in my case I am using “activity_main.xml” and included the “YouTubePlayerView” as like below.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.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="com.androidmad.ytubeapi.MainActivity">
    
        <com.google.android.youtube.player.YouTubePlayerView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:id="@+id/yt_pv"/>
    
    </android.support.constraint.ConstraintLayout>
  2. We need to initialize & load the video to YouTubePlayerView. So, open or create an activity file. In my case I am using “MainActivity.kt”.
  3. To initialize the YouTube Player add the implementation of “YouTubePlayer.OnInitializedListener” as like below.
  4. YouTubePlayer is initialized by calling Initialize method with Android API key and its initialization listener.
    class MainActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener {
    
        override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {
        }
    
        override fun onInitializationFailure(p0: YouTubePlayer.Provider?, p1: YouTubeInitializationResult?) {
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            yt_pv.initialize(DeveloperApiKey, this)
        }
    }
    Here, DeveloperApiKey – a variable for Android API Key. In Kotlin, we can directly access the view in design or layout file from code behind using kotlinx for Android
  5. We can load or cue the YouTube video by its id after the YouTube Player initialized successfully like below
    override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {
     showShortToast("Youtube Api Initialization Success")
     if (!wasRestored) {
      player?.cueVideo("wKJ9KzGQq0w");
     }
    }
    Here, showShortToast is an extension method created to Show Toast with short duration. To know about extensions, please read my previous article on Kotlin.

Full Code:

You can find the full code implementation of the Activity here.

class MainActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener {

    override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {
        showShortToast("Youtube Api Initialization Success")
        if (!wasRestored) {
            player?.cueVideo("wKJ9KzGQq0w");
        }
    }

    override fun onInitializationFailure(p0: YouTubePlayer.Provider?, p1: YouTubeInitializationResult?) {
        showShortToast("Youtube Api Initialization Failure")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        yt_pv.initialize("API KEY", this)
    }
}

Reference:

YouTube Android Player API https://developers.google.com/youtube/android/player/
YouTube API Client Library Downloads https://developers.google.com/youtube/android/player/downloads/
Kotlin Extensions (Previous Article) https://www.androidmads.info/2019/06/how-to-use-extensions-method-in-kotlin.html
Extensions in Kotlin https://kotlinlang.org/docs/reference/extensions.html

If you have any doubt or need any help, contact me.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.


Share this

Related Posts

Latest
Previous
Next Post »

Please Comment about the Posts and Blog