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
- Open Google API Console.
- Create a new project or choose your existing project in the API Console.
- Open API page and search for the YouTube Android Player API.
- Then select enable API and go to credentials page.
- 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.
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:
- Open Android Studio and select "Create new project".
- Name the project as your wish and tick the Kotlin Support checkbox.
- Then Select your Activity type (For example, Navigation Drawer Activity, Empty Activity, etc.).
- 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.
- 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 the “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. 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 the 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
- 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("AIzaSyDv-gjtmZh1h9WKwQbp-aySccEFlDkxFuk", 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 on
GitHub. Hit like the article.