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
- Download YouTube API client library from the following link, basically this library is a jar file. https://developers.google.com/youtube/android/player/downloads/
- 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:
- Open Google API Console.
- Create a new project or choose your existing project in API Console.
- Open API page and search for YouTube Android Player API.
- Then select enable API and go to credentials page.
- 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
- Open Android Studio and select "Create new project".
- Name the project as per your wish and tick the "Kotlin checkbox support".
- Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
- 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.
- With respect to our previous step, we have already downloaded the API client library for YouTube API as a Zip file.
- Then extract the jar files and add them to “libs” folder.
- Then open app level build.gradle file and add the following lines in dependencies.
dependencies { … implementation files('libs/YouTubeAndroidPlayerApi.jar') … }
- Then click “Sync Now” to setup your project.
- 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).
- 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>
- We need to initialize & load the video to YouTubePlayerView. So, open or create an activity file. In my case I am using “MainActivity.kt”.
- To initialize the YouTube Player add the implementation of “YouTubePlayer.OnInitializedListener” as like below.
- YouTubePlayer is initialized by calling Initialize method with Android API key and its initialization listener.
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 Androidclass 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) } }
- We can load or cue the YouTube video by its id after the YouTube Player initialized successfully like below
Here, showShortToast is an extension method created to Show Toast with short duration. To know about extensions, please read my previous article on Kotlin.override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) { showShortToast("Youtube Api Initialization Success") if (!wasRestored) { player?.cueVideo("wKJ9KzGQq0w"); } }
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.
Follow Us
Were this world an endless plain, and by sailing eastward we could for ever reach new distances