Dec 24, 2012

YouTube Android Player API Tutorial


YouTube Android API is experimental
"The YouTube Android Player API is an experimental API version, which means it is still in development, though we do not expect major interface changes. Until the experimental label is removed, the Deprecation Policy for YouTube APIs won't apply to this version as discussed in the API Terms of Service."

Note:
  • Users need to run version 4.2.16 of the mobile YouTube app (or higher) to use the API.
  • Change API Key before compiling & running source code.
Let's make simple demo using YouTube Android API. Demo contains one EditText and YouTubePlayerView. Just Provide YouTube video id and press "Go" button to start video.



Step 1 : Download YouTube Android API :  download

Step 2 : Create Android Project named "YouTubeAPIDemo" using eclipse.

Step 3 : Register this demo to get API key

https://developers.google.com/youtube/android/player/register

Step 3 : Unzip YouTube Android API.
             Go to folder -> libs
             Copy "YouTubeAndroidPlayerApi.jar"
             Paste in Android Project : YouTubeAPIDemo->libs
             Right click on YouTubeAndroidPlayerApi.jar -> Build Path -> Add to build path.

 Step 4 : Add YouTube Video Player View in activity_main.xml, player view display in bold.

<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"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="#C0C0C0"
        android:text="Enter Only Video ID in below EditText example : https://www.youtube.com/watch?v=fhWaJi1Hsfo"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <EditText
        android:id="@+id/eturl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:hint="Enter YouTube URL and Press Enter"
        android:text="fhWaJi1Hsfo"
        android:singleLine="true"
        android:imeOptions="actionGo" >
    </EditText>

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtubeplayer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/eturl"
        >
    </com.google.android.youtube.player.YouTubePlayerView>
    
</RelativeLayout>

Step 5 : Let's modify main activity code

package com.kpbird.youtubeapidemo;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
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.Provider;
import com.google.android.youtube.player.YouTubePlayerView;

public class MainActivity extends YouTubeBaseActivity 
 implements YouTubePlayer.OnInitializedListener,OnEditorActionListener {

 private YouTubePlayerView ytpv;
 private YouTubePlayer ytp;
 private EditText et;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  ytpv = (YouTubePlayerView) findViewById(R.id.youtubeplayer);
  ytpv.initialize("AIzaSyC-R09MYt2HS82nxKuFCzvNgC60DnxFcqM", this);
  
  et = (EditText) findViewById(R.id.eturl);
  et.setOnEditorActionListener(this);
 }

 @Override
 public void onInitializationFailure(Provider arg0,YouTubeInitializationResult arg1) {
  Toast.makeText(this, "Initialization Fail", Toast.LENGTH_LONG).show();
 }

 @Override
 public void onInitializationSuccess(Provider provider, YouTubePlayer player,boolean wasrestored) {
  ytp = player;
  Toast.makeText(this, "Initialization  Success", Toast.LENGTH_LONG).show();
 }

 @Override
 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
  if(actionId == EditorInfo.IME_ACTION_GO ){
   if(ytp !=null){
    ytp.loadVideo(et.getText().toString());
   }
  }
  return false;
 }
}
  • Extends class with YouTubeBaseActivity
  • Implements YouTubePlayer.OnInitializedListener 
  • Call initialize method with API key and class object
  • YouTubePlayer.loadVideo(<video id>)
You have to use YouTubeBaseActivity instand of Activity and implement interface named "YouTubePlayer.OnInitializedListener" to check initialization status and to get YouTubePlayer control.

Download Demo : Click
[ File->Download to download entire zip file]

Reference
  1. https://developers.google.com/youtube/android/player/
  2. https://developers.google.com/youtube/android/player/register
  3. https://developers.google.com/youtube/android/player/register


12 comments:

  1. I am asking this question to everywhere I come accross.

    In all the blog posts and tutorials, they are saying that there is a possibility that we can display ads in Youtube Player API. How can we do that? I am displayin a youtube video that has ads in it in desktop environment but not in my Android application. Besides I want to display video ads. How can we do those?

    ReplyDelete
  2. Hello Said,

    If you want to display ads inside YouTubePlayer same as Desktop, I don't think It is possible right now but You can integrate Google AdMob in Android application and place admob layout below your YouTubePlayerView.

    For more information you can contact to Reto Meier, He is right guy to ask inside questions - https://plus.google.com/111169963967137030210/about

    ReplyDelete
  3. Of course I can integrate admob ads. Even in the official blog post of Youtube Player API, they have mentioned about the ads in YoutubeplayerView. But the did not mention anything about how to do that.

    ReplyDelete
  4. There is a problem in the intialization ots not working

    ReplyDelete
  5. Sandeep T3:06 PM

    i am getting error like:An error occurred while intializing the YouTube Player

    ReplyDelete
  6. kpbird3:34 PM

    Please post your error. so I can help you better

    ReplyDelete
  7. pishty Agha2:22 AM

    do you know how i can get the title of the video ?

    ReplyDelete
  8. kpbird4:36 PM

    Hello Pishty Agha,

    According to Classes & Interface list, I don't think YouTubePlayer API provide title of video. Reference : https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubePlayerView

    YouTube provide data api , web service, You can fetch title and all other information using data api. https://developers.google.com/youtube/v3/

    ReplyDelete
  9. Initialization Success but video not show up

    ReplyDelete
  10. Initialization Succes but why cant load youtube ?

    ReplyDelete
  11. 3ncrypt06:49 PM

    Hey,

    is it correct, that the youtube api required the youtube app? my app shows me the message: "An error occurred while intializing the YouTube Player". now i have downloaded the youtube app an it works....

    ReplyDelete
  12. Vikram Mahadevan8:34 PM

    I am trying to embed 2/multiple YouTubePlayerViews dynamically onto a linear layout and I notice that only the last one is playable. The rest of them seem like they initialize and then get uninitialized. Here's a snippet of my code:

    package test.at.xyz;

    import com.google.android.youtube.player.YouTubePlayer;

    import com.google.android.youtube.player.YouTubePlayer.Provider;

    import com.google.android.youtube.player.YouTubePlayerView;

    public class PostActivity extends YouTubeFailureRecoveryActivity{

    LinearLayout llPostContent;



    ArrayList videopc = new ArrayList();

    ArrayList ytpva = new ArrayList();

    int currentVideo = -1;



    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.post);



    getUIandInitialize();

    }



    public void getUIandInitialize(){

    llPostContent=(LinearLayout)findViewById(R.id.llPostContent);

    Post pst = ((GlobalVars) this.getApplication()).getCurrentPost();

    ArrayList pcs = pst.getPostContent();

    if(pcs.size() > 0) {

    for(int i=0; i < pcs.size(); i++) {

    addPC(pcs.get(i));

    }

    }

    }

    public void addPC(PostContent pc) {

    LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    lparams.setMargins(10, 10, 10, 0); // llp.setMargins(left, top, right, bottom);

    switch(pc.type) {

    case 4:

    currentVideo++;

    videopc.add(pc);

    YouTubePlayerView yv=new YouTubePlayerView(this);

    yv.setLayoutParams(lparams);

    ytpva.add(yv);

    yv.initialize("DSFDSFDSFSDFSDFDSFSFDDFFSD", this);

    this.llPostContent.addView(yv);

    break;

    }

    }



    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored)

    {

    if (!wasRestored) {

    player.cueVideo(videopc.get(currentVideo).content);

    }

    }

    @Override

    protected Provider getYouTubePlayerProvider() {

    return ytpva.get(currentVideo);

    }



    }

    ReplyDelete