April 19, 2024

How To Make The Use Of YouTube Player View In Android

5 min read

This post is about the use of Youtube Player API in android development. Experts working with IT companies are also explaining the use of Google API key in this article. Read this article and learn how professionals of android development India apply YouTube player API in android.

Android platform have lots of applications in market and each application uses its own data like images, videos, audio etc to attract the users to use application’s features. Some of the applications uses these data for demonstration of itself and some applications uses these type of data for better user experience. Data like images and audio require less space than videos so it can be stored inside the application but videos can increase the size of our application so most applications uses its server to store fetch the video to display inside application. If there is no server for an application then developer will upload the video on Youtube and uses the YoutubePlayer api to display the video inside the application.

Nowadays using of graphics like images, videos, GIFs etc is common in applications. Some application uses these type of data for demonstration and some uses these type of data as content of the application. YoutubePlayer api allows the user to stream the video inside any application. To stream the video inside application youtube provides a player view named Youtube Player View. To use youtube player view, youtube api provides some methods to load and play the video from youtube to our player view inside the application. Youtube Player api also provides the methods for customizing and controlling the playback of video inside youtube player view.

We can load or put the video in queue into the player view of youtube inside our application UI. The api provides us the ability to control the playback programmatically. I.e. play, pause or seek the video to specific point inside the video currently loaded into the player. Youtube player api provides the methods for the visibility of controls inside the player view. So we can hide or display the controls of players in our application. Many applications uses youtube player view to display intro of an application’s overview with hidden controls of the youtube player view.

Youtube player api provides three methods to handle the visibility of youtube player view’s controls in our application. First is Chromeless, this will completely hide the controls of player so we can use the player to play the video as applications intro or demonstration. Second is Default, this will display all the controls that youtube api provides for its player so that user can pause, play or seek the video inside our application. Third is Minimal, this will display the progress and pause button inside the player but we cannot seek the video.

Youtube api provides two ways to stream the youtube video in our application, by using Youtube Player View and by using Youtube Player Fragment. Here we will user Youtube Player View to display the usage of streaming videos inside our application.

Dependency:

To use youtube player view we need to download the api client library from https://developers.google.com/youtube/android/player/downloads/.

After downloading the library we will extract the jar file named YoutubeAndroidPlayerApi.jar from libs directory and place this jar file inside our application’s libs directory so that all the classes and view of YouTube player will be available to our application. Our application’s structure will look like below image.

We can also find an example inside the client api library that we have downloaded previously.

Google API Key:

After adding dependency to the project now we need the Google Api Key to use the YouTube Player Api to stream the video in our application. Below are steps on how to get an api key for our application.

  • Open Google Developer Console and create a new project with same name as our application.
  • After creating project open sidebar from left and click on library, click on YouTube Data API and click on Enable which is in blue color next to the YouTube Data API V3 title on top.
  • Now from the sidebar click on Credentials, click on Create Credentials drop down where API Key option will displayed click on it.
  • In pop up we have to select Android Key to specify our key type. Next we have to select Add Package name and fingerprint and we will add our application’s package name and we will add the SHA-1 fingerprint of our signing certificate.
  • Finally click on Create button to generate API Key.

This key will be used in our application to allow our application to use YouTube Player Api. It is necessary to generate an Api key from developer console otherwise our application could not stream YouTube videos.

Design:

Now that we have added the dependency and generated the api key next we will put our youtube player view inside our layout as described in below layout file.

layout/activity_main.xml :

<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:padding="5dp"

    tools:context="com.example.youtubeplayerdemo.MainActivity">

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="YoutubePlayer Example"

        android:gravity="center"

        android:textSize="18dp"

        android:textColor="@android:color/black"

        android:layout_above="@+id/video_player"

        android:layout_marginBottom="10dp"

        android:id="@+id/tv_info"/>

    <com.google.android.youtube.player.YouTubePlayerView

        android:id="@+id/video_player"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:minHeight="110dp"/>

</RelativeLayout>

In above layout file we can see that we have one TextView to display the title above youtube player view. Below that we have put the YoutubePlayerView which comes from the jar file which we have added in our libs directory.

The Activity :

We will use the layout file we created above in our activity and override the methods of Youtube Player View to make it work.

MainActivity.java :

public class MainActivity extends YouTubeBaseActivity implements OnInitializedListener{

    public static final String GOOGLE_API_KEY = "AIzaSyBDU2khiuLHduf-EOCugkf4m3KxV0mM3WY";

    public static final String YOUTUBE_VIDEO_ID = "mcixldqDIEQ";

    public static final int REQUEST_CODE_ERROR = 100;

    YouTubePlayerView youtubePlayer;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        youtubePlayer = (YouTubePlayerView)findViewById(R.id.video_player);

        youtubePlayer.initialize(GOOGLE_API_KEY,this);

    }

    @Override

    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

        youTubePlayer.loadVideo(YOUTUBE_VIDEO_ID);

        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);

    }

    @Override

    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

        if(youTubeInitializationResult.isUserRecoverableError()){

            youTubeInitializationResult.getErrorDialog(this,REQUEST_CODE_ERROR);

        }

    }

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == REQUEST_CODE_ERROR){

            youtubePlayer.initialize(GOOGLE_API_KEY,this);

        }

    }

}

As we can see that we have extends Youtube Api’s YoutubeBaseActivity instead of Activity. It is mandatory because it contains some methods related to YoutubePlayerView’s initialization, start, stop etc. We have also implemented the interface called OnInitializedListener which is used as callback when initializing our youtube player view. It provides two overridden methods, First is onInitializationSuccess(…) which is responsible to initialize our player with video id and other customization of YoutubePlayerView. Second is onInitializationFailure(…) which is used to handle any error during playback or during initialization of video. We have overridden onActivityResult(…) of an activity so that we can display the error if occurred and initialize the player again after message displayed. GOOGLE_API_KEY variable will hold the Api Key that we have created previously from Developer Console.

Application Screens:

   

You can use Youtube Player API and in android and load and play the video you your player view inside the application. If you have any doubt or query, you can put it in the comments below and wait for android development India experts to respond your query.

Leave a Reply

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