YouTube Player API In Android Using Kotlin

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, cue, and play videos. It has 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 interacts with a service that is a part of the YouTube app.
 
Before going to the coding part, we need to follow the below steps for setting up the YouTube API in our own developed app
  • Download YouTube API client library from this link, basically this library is a jar file.
  • 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 a must for using this API.

Register app and get Android API Key

  1. Open Google API Console.
  2. Create a new project or choose your existing project in the API Console.

    YouTube Player API In Android Using Kotlin

  3. Open API page and search for the YouTube Android Player API.
  4. Then select enable API and go to credentials page.

    YouTube Player API In Android Using Kotlin

  5. Then select API Key will create your API key. We can improve the security of the API key with package name & SHA key of your system.

    YouTube Player API In Android Using Kotlin

Coding Part

 
I have detailed the article as in the following steps.
  • Step 1: Creating a New Project with Empty Activity.
  • Step 2: Setting up the YouTube Library and Manifest.
  • Step 3: Integration of YouTube Android Player in Screen using Kotlin.
Step 1 - Creating a new project with Kotlin:
  1. Open Android Studio and select "Create new project".
  2. Name the project as your wish and tick the Kotlin Support checkbox.
  3. Then Select your Activity type (For example, Navigation Drawer Activity, Empty Activity, etc.).

    YouTube Player API In Android Using Kotlin

  4. Then 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 set up 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 the “libs” folder.

    YouTube Player API In Android Using Kotlin

  3. Then open app level build.gradle file and add the following lines in dependencies.
    1. dependencies {   
    2.    …  
    3.    implementation files('libs/YouTubeAndroidPlayerApi.jar')     
    4.     …  
    5. }  
  1. Then click “Sync Now” to setup your project.
  2. Now, the project is ready. Add internet permissions in AndroidManifest.xml.
    1. <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.
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
    4.     xmlns:tools="http://schemas.android.com/tools"  
    5.     android:layout_width="match_parent"  
    6.     android:layout_height="match_parent"  
    7.     tools:context="com.androidmad.ytubeapi.MainActivity">  
    8.   
    9.     <com.google.android.youtube.player.YouTubePlayerView  
    10.         android:layout_width="wrap_content"  
    11.         android:layout_height="wrap_content"  
    12.         app:layout_constraintBottom_toBottomOf="parent"  
    13.         app:layout_constraintLeft_toLeftOf="parent"  
    14.         app:layout_constraintRight_toRightOf="parent"  
    15.         app:layout_constraintTop_toTopOf="parent"  
    16.         android:id="@+id/yt_pv"/>  
    17.   
    18. </android.support.constraint.ConstraintLayout>  
  1. We need to initialize & load the video to YouTubePlayerView. So, open or create an activity file. In my case, I am using “MainActivity.kt”.
  2. To initialize the YouTube Player add the implementation of “YouTubePlayer.OnInitializedListener” as like below.
  3. YouTubePlayer is initialized by calling the Initialize method with Android API key and its initialization listener.
    1. class MainActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener {    
    2.     override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {    
    3.     }    
    4.     override fun onInitializationFailure(p0: YouTubePlayer.Provider?, p1: YouTubeInitializationResult?) {    
    5.     }    
    6.     override fun onCreate(savedInstanceState: Bundle?) {    
    7.         super.onCreate(savedInstanceState)    
    8.         setContentView(R.layout.activity_main)    
    9.         yt_pv.initialize(DeveloperApiKey, this)    
    10.     }    
    11. }   
    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
  1. We can load or cue the YouTube video by its id after the YouTube Player initialized successfully like below,
    1. override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {  
    2.         showShortToast("Youtube Api Initialization Success")  
    3.         if (!wasRestored) {  
    4.             player?.cueVideo("wKJ9KzGQq0w");  
    5.         }  
    6.     }  
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.
  1. class MainActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener {  
  2.   
  3.     override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {  
  4.         showShortToast("Youtube Api Initialization Success")  
  5.         if (!wasRestored) {  
  6.             player?.cueVideo("wKJ9KzGQq0w");  
  7.         }  
  8.     }  
  9.   
  10.     override fun onInitializationFailure(p0: YouTubePlayer.Provider?, p1: YouTubeInitializationResult?) {  
  11.         showShortToast("Youtube Api Initialization Failure")  
  12.     }  
  13.   
  14.     override fun onCreate(savedInstanceState: Bundle?) {  
  15.         super.onCreate(savedInstanceState)  
  16.         setContentView(R.layout.activity_main)  
  17.         yt_pv.initialize("AIzaSyDv-gjtmZh1h9WKwQbp-aySccEFlDkxFuk"this)  
  18.     }  
  19. }  
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 on GitHub. Hit like the article.


Similar Articles