Embed Video in your Android Application Using YouTube Android Player API v1.2.1
With YouTube Android Player API, you can embed videos and playlists into your application. User gets playback and controlling experience much similar Official YouTube Android Application. User can control loading and playing of embedded YouTube video. Playing, cueing and loading can be controlled programmatically as well. Event listeners api’s with support of events like open fullscreen or player loading etc gives you complete control that you would desire of.
YouTube Android Player Api client library is dependent on YouTube Application, it interacts with services part of YouTube application for video playback.
Step 1. Registering application with Google Developers Console
1.1 Go to Google Developers Console, Create a new project if none exists or select an existing project.
1.2 Navigate to APIs & auth -> APIs in left sidebar, browse for YouTube Data API v3 and turn on its status accepting terms of services.
1.3 Generate SHA1 fingerprint using java keytool utility
For getting API key, we need to generate SHA-1 fingerprint using java keytool. Open your command prompt and execute the below mentioned command to generate SHA-1 fingerprint. If keytool is not recognized, you can find it in bin directory of installed jre. In my case C:\Program Files\Java\jre7\bin.keytool -list -v -keystore “%USERPROFILE%\.android\debug.keystore” -alias androiddebugkey -storepass android -keypass android
From output note down SHA1 output, “FD:0E:04:E9:99:28:B9:3D:E7:AC:75:AF:6E:2B:F6:E7:CD:EE:CA:96″ in my case.
1.4 Generate API Key
Navigate to APIs & auth -> credentials in left sidebar, select Create New Key and opt for Android key.
Enter your SHA1 fingerprint and application package name sperated by semi-colon(;) and select create. It will generate API key for your application. Note down API key for later usage. API Key generated in my case is AIzaSyBcTwxVG7eYC314bzw1D28XwFi5xe6DT7k.
Step 2. Developing Sample Application using YouTube Android Player API
2.1 Create new Android Application Project in Eclipse with package name.
2.2 Download latest version 1.2.1 of YouTube Android Player API and extract downloaded file.
2.3 From extracted files, copy YouTubeAndroidPlayerApi.jar from libs folder to add it to libs folder of your android application.
2.4 Preparing Application Manifest File
Add android.permission.INTERNET
permission to access Internet. We will have just one activity in our application which will embed YouTube video.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidsrc.youtubeapidemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.androidsrc.youtubeapidemo.PlayVideoActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
2.5 Preparing Layout File
In layout file, add com.google.android.youtube.player.YouTubePlayerView
view which will used for video playback. Modify your launcher activity layout as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_marginTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="@android:style/TextAppearance.Large" android:gravity="center" android:textColor="@android:color/holo_blue_dark" android:text="YouTubePlayerView\nhttp://cs2guru.com"/> <com.google.android.youtube.player.YouTubePlayerView android:id="@+id/youtube_view" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> |
2.6 Preparing Launcher Activity
For embedding YouTube video in an activity. We must take care of two points.
1. In order to incorporate YouTubePlayerView
views in your UI, you must extend YouTubeBaseActivity
.
2. Implement YouTubePlayer.OnInitializedListener
for listening to intialization callback of success or failure. We set this callback while intializing YouTubePlayerView.
In case of successful intialization of YouTubePlayerView, we get object of YouTubePlayer which can be used to control player programmatically to cue videos and control playback etc. For failure case, we check if it is recoverable error then we reinitialize YouTubePlayerView.
For listening to fullscreen change events, we can use YouTubePlayer.OnFullscreenListener
1 2 3 4 5 6 7 8 9 |
private class FullScreenListener implements YouTubePlayer.OnFullscreenListener{ @Override public void onFullscreen(boolean isFullscreen) { //Called when fullscreen mode changes. } } |
For listening to playback events like buffering, play, pause, seek and stop, you can use YouTubePlayer.PlaybackEventListener
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
private class PlaybackListener implements YouTubePlayer.PlaybackEventListener{ @Override public void onBuffering(boolean isBuffering) { // Called when buffering starts or ends. } @Override public void onPaused() { // Called when playback is paused, either due to pause() or user action. } @Override public void onPlaying() { // Called when playback starts, either due to play() or user action. } @Override public void onSeekTo(int newPositionMillis) { // Called when a jump in playback position occurs, //either due to the user scrubbing or a seek method being called } @Override public void onStopped() { // Called when playback stops for a reason other than being paused. } } |
For listening to player state change events, implement YouTubePlayer.PlayerStateChangeListener
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
private class PlayerStateListener implements YouTubePlayer.PlayerStateChangeListener{ @Override public void onAdStarted() { // Called when playback of an advertisement starts. } @Override public void onError(ErrorReason reason) { // Called when an error occurs. } @Override public void onLoaded(String arg0) { // Called when a video has finished loading. } @Override public void onLoading() { // Called when the player begins loading a video and is not ready to accept commands affecting playback } @Override public void onVideoEnded() { // Called when the video reaches its end. } @Override public void onVideoStarted() { // Called when playback of the video starts. } } |
Our main activity code will be as below. For cueing videos in YouTubeVideoPlayer, we need to provide video id for it. I have taked video id for song “Let It Go” from Frozen movie. On intialization of view, we will cue this video. For keeping it simple, i have just used initialization listener.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
package com.androidsrc.youtubeapidemo; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayer.ErrorReason; import com.google.android.youtube.player.YouTubePlayer.Provider; import com.google.android.youtube.player.YouTubePlayerView; public class PlayVideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { private static final int RECOVERY_DIALOG_REQUEST = 10; public static final String API_KEY = "AIzaSyBcTwxVG7eYC314bzw1D28XwFi5xe6DT7k"; //From URL -> https://www.youtube.com/watch?v=kHue-HaXXzg // Let It Go : "Frozen" private String VIDEO_ID = "kHue-HaXXzg"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.playerview_demo); YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view); youTubeView.initialize(API_KEY, this); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) { if (errorReason.isUserRecoverableError()) { errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show(); } else { String errorMessage = String.format("YouTube Error (%1$s)", errorReason.toString()); Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); } } @Override public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) { if (!wasRestored) { player.cueVideo(VIDEO_ID); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RECOVERY_DIALOG_REQUEST) { // Retry initialization if user performed a recovery action getYouTubePlayerProvider().initialize(API_KEY, this); } } protected YouTubePlayer.Provider getYouTubePlayerProvider() { return (YouTubePlayerView) findViewById(R.id.youtube_view); } } |
2.7 Build and Run your Application
If you have completed all steps above carefully, build and run your application. You will see YouTube video embedded in your application.