All CategoriesAndroid App Development

Usage of YouTube API's in Video Streaming Application

Introduction

YouTube API performs an important role to play or load the video in our Android Application.
If we want to show the video in our application with our video player, then it will increase the size of the app. So, instead of using this, YouTube provides its API to integrate YouTube Player in our application.
By using this, we can easily stream the video, and it is very efficient for our application.
We can show the playlists, and do other operations like play, pause or seek the current video at a specific time by using this API.
It also provides the functionalities of orientation changes to play the video in full screen.

YouTubePlayerView:

YouTube API provides this view. It manages the configuration changes. Also, it saves and restores the state of YouTubePlayer which is associated with the view as part of the onSaveInstanceState / onRestoreInstanceState.

Custom Player Controls:

Inside this API it provides some controls to the user to customize the application.
By using these controls, the user can jump the video at a specific time easily.

This API gives two methods to jump playback:

seekToMillis(): This method helps to seek the video at specified time.
seekRelativeMillis(): This method seeks forward or backward by the specified number of seconds.

YouTubePlayer Interfaces:

YouTubePlayer provides many interfaces to take action on different events like buffer, play, pause, stop, seek, etc.

Interfaces are:

YouTubePlayer.PlayerStateChangeListener:

This interface needs to be implemented when the high-level player state changes.

YouTubePlayer.PlayBackEventListener: 

This interface needs to be implemented when video playback events occur.

YouTubePlayer.OnFullscreen Listener: 

This interface needs to be implemented when the player toggles between fullscreen on or off.

YouTubePlayer.PlayListEventListener: 

This interface needs to be implemented when events related to playlist occur

YouTubePlayer.OnInitializedListener:

This interface needs to be implemented to listen for the initialization is success or failure.
So, these are the interfaces. We will implement the last one in our application and override its method to show the functionalities like to play the jkvideo and show the error if not play successfully.

Register the application:

Before going to create a YouTube application we have to register the application on google developer console and get the Android key.

So, follow the simple steps:

  • Go to the Google developer console and create a new project.
  • After this select the API’s and enable the YouTube Data API v3.

  • After this, by using SHA-1 fingerprint give the package name of your Android application and generate the Android key.

  • Press Save button.

  • Here, we can see very well that our Android key is generated. Now, use this key in our application.

Get the Library:

This library is very important to create YouTube video streaming application.

  • Download the latest version of YouTube player API from the official website.
  • After Download extract it. There are several folders, from there get the YouTubeAndroidPlayerApi.jar.
  • Paste this jar file in your libs directory.

Example with code: 

Here, we are going to create a video streaming application by using YouTube API. It shows a welcome screen with a YouTubePlayerView. It performs all the functionalities of YouTube video in your android application.

  • Create an Application YouTubeExampleAndroid.
  • Add the library successfully in your project.
  • Give the Internet Permission in AndroidManifest.xml file.

AndroidManifest.xml:

Give the internet permission in this file.

Add the code here:

<uses-permission android:name="android.permission.INTERNET"/>

Requirements:

Create this separate class in your project to define the configuration variables. Here, we paste the generated Android key and YouTube video code.

Add the code here:

public class Config {
	 public static final String DEVELOPER_KEY = "AIzaSyC5lyioipD0SpJ0UJ5hxz-EDVnO1gZyeI4";
     public static final String YOUTUBE_VIDEO_CODE = "fhWaJi1Hsfo";
}

activity_main.xml:

This is our main layout file. As we discussed above, here we will define Welcome text and our YouTubePlayerView. It is used to show the YouTube videos.

Add the code here:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.youtubeapiexampleandroid.MainActivity" >
    <TextView
        android:id="@+id/tv_WelcomeText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/welcomeText"
        android:textColor="#0000ff"
        android:textStyle="bold"
        android:textSize="22dp"/>
    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_WelcomeText"
        android:layout_marginTop="20dp"/>
</RelativeLayout>

MainActivity.java:

To create the YouTubePlayerView this activity needs to be extends with YouTubeBaseActivity class. Here, we will take the reference of YouTubePlayerView and initialize it with the help of Android key.
Initialize:

private YouTubePlayerView youTubeView;

Add the code in onCreate(){..}:

youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(Config.DEVELOPER_KEY, this);

As we discussed above. Here, it implements YouTubePlayer.OnInitializedListener interface which listen for initialization success or failure. It gives us two methods i.e.

onInializationSuccess(..):

If initialization is successful then this method is called and it plays the video by using cueVideo() method.

Add the code here:

@Override
    public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
        if (!wasRestored) {
            player.cueVideo(Config.YOUTUBE_VIDEO_CODE);
        }
    }

onInitializationFailure(…):

If initialization is failed, then this method is called. Here, first, it will see the error is recoverable or not. If yes then it shows the error dialog to recover the error by using getErrorDialog() method and if not then it shows the toast message of error.

Add the code here:

@Override
    public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
        if (errorReason.isUserRecoverableError()) {
            errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
        } else {
            String error = String.format(getString(R.string.player_error), errorReason.toString());
            Toast.makeText(this, error, Toast.LENGTH_LONG).show();
        }
    }

If user performed a recovery action then onActivityResult() method is called. It is used for retry initialization.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECOVERY_REQUEST) {
            getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
        }
    }

Now, Run the Application and see the Output.

Output:


 

Download Source Code: GitHub

Conclusion:

So, this is the simple example of How to use YouTube API to play video streaming application in Android. As we discussed above by using YouTube library and creating android key we can easily develop an application. There are many apps which are using this API and build powerful applications. It is beneficial for us because it saves the space of the application and streams the video easily. There are lots of functionalities in this library which can customize and makes our application better. It is very important and popular in Android development.
Keep visiting www.acadgild.com for more updates on the courses.
Android Programming

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close