Tutorials Android YouTubePlayerView Example in Android Using YouTube API

YouTubePlayerView Example in Android Using YouTube API

Jack and Jill says this tutorial is retired. And we agree! This tutorial was published back in May 2014, since then lot has been changed; YouTubePlayerAPI is updated and Eclipse for Android development is history. Checkout our new YouTube Android Player API Example here.

In this tutorial we’ll see how to use YouTube Player API in android. YouTube player API provides an embedded view that supports with various playback controls.

1. Downloading YouTube Player API

Before you start writing some code, you’ll have to first download the YouTube Android Player API. Once downloaded import the jar into your project lib folder and add the jar to your build path.

Download YouTube Player API here

YouTube Android Player API

2. Register your app in Google developer console

  • Before you start using the Youtube player API for android, you have to register your application with Google developer console and get and API key, The API key is a unique value for your application. Do not disclose this to others.
  • Visit Google APIs Console and login with your Google account and create a new project
  • Once your project is created, got to API’s and enable YouTube data API V3
  • And then Select API Access in your API Console. You’ll find API key. This API key will be used to access YouTube Android Player APIs.

YouTube Android Player API2

3. Create a new Android Application project

Now you are ready to create Android project to play YouTube videos using YouTube player API. You may use IDE of your choice, here I am using Eclipse.

You need INTERNET permission to play video over internet. Add below permission in your application AndroidManifest.xml file.

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

4. Define your activity layout

In this example, we will create an simple layout that uses YouTubePlayerView inside an LinearLayout.

<LinearLayout 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:orientation="vertical" >

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_player"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:padding="5dp" />

</LinearLayout>

5. Initialize YouTubePlayerView in your Activity

Initializing YouTube player view by calling initialize methood. Once the initialize is successful, you will get the onInitializationSuccess() callback with YouTubePlayer instance. You can add additional listeners to handle the playback control events.

package com.javatechig.youtubeapp;

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.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import com.javatechig.youtubeandroid.R;

public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
	public static final String API_KEY = "YOUR API KEY";

	//http://youtu.be/<VIDEO_ID>
	public static final String VIDEO_ID = "dKLftgvYsVU";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/** attaching layout xml **/
		setContentView(R.layout.activity_main);

		/** Initializing YouTube player view **/
		YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
		youTubePlayerView.initialize(API_KEY, this);
	}

	@Override
	public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
		Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
		/** add listeners to YouTubePlayer instance **/
		player.setPlayerStateChangeListener(playerStateChangeListener);
		player.setPlaybackEventListener(playbackEventListener);

		/** Start buffering **/
		if (!wasRestored) {
			player.cueVideo(VIDEO_ID);
		}
	}

	private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {

		@Override
		public void onBuffering(boolean arg0) {
		}

		@Override
		public void onPaused() {
		}

		@Override
		public void onPlaying() {
		}

		@Override
		public void onSeekTo(int arg0) {
		}

		@Override
		public void onStopped() {
		}

	};

	private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {

		@Override
		public void onAdStarted() {
		}

		@Override
		public void onError(ErrorReason arg0) {
		}

		@Override
		public void onLoaded(String arg0) {
		}

		@Override
		public void onLoading() {
		}

		@Override
		public void onVideoEnded() {
		}

		@Override
		public void onVideoStarted() {
		}
	};
}

6. Output
YouTube Android Player API Example - Javatechig

Total
0
Shares
guest
47 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Joao Paulo Fricks
Joao Paulo Fricks
7 years ago

It’s possible to show us how get a youtube playlist?

javatechig
javatechig
7 years ago

Yes. Very much possible. Youtube has their own API for public usages.

Look at official documentation https://developers.google.com/youtube

javatechig
javatechig
7 years ago

which device you testing on?

Ngọc
Ngọc
7 years ago

I tried to to like that but i got many bugs. How do I fix it? I run on Genymotion

This is XML file http://ideone.com/RbXit1

and then MainActivity http://ideone.com/bHlPM6

i m bond
i m bond
7 years ago
Reply to  Ngọc

add youtube library in lib folder too and after that run it again

Sanid Kankaeng
Sanid Kankaeng
7 years ago

can i use more than a YouTubePlayerView in once activity

javatechig
javatechig
7 years ago
Reply to  Sanid Kankaeng

Yes. You can….

Wejdan
Wejdan
7 years ago

thank you, it’s a very helpful tutorial!
i tried that but i got “Failured to Initialize!” =( can you tell me why?

javatechig
javatechig
7 years ago
Reply to  Wejdan

Checkout your API key. that can be a culprit.

dreamgs1
dreamgs1
7 years ago

Hi,

I have a fragmnet called FragmnetVideo which is one of 4 fragmnets managed by FragmnetStatePageAdaper.

This FragmetVideo is called with a youtube video link which should be played once your scrolls to that fragment and clicks on play.

How can I do the same in a fragmnet.

I have already tried youtubeplayerfragment but i am not able to get it worked. I am new to android development

below is the same query posted:

http://stackoverflow.com/questions/26108197/youtubeplayerfragmnet-unable-to-create-a-fragment-to-play-youtube-video

Could you please give some pointers

javatechig
javatechig
7 years ago

Yes! you can.

javatechig
javatechig
7 years ago

Oh, I see. By the way the code was not tested on Lollypop. Will take this and review for any changes if required.

Sebbe
Sebbe
7 years ago
Reply to  javatechig

Does this still not work with Lollopop? and how come it doesnt work with it?

Evans Kakpovi
Evans Kakpovi
7 years ago

how do you add support for age-restricted videos?

JavaTechig
JavaTechig
7 years ago

Take a look at youtube JSON API developer guide

https://developers.google.com/youtube/2.0/developers_guide_json

Ashish Bhagat
Ashish Bhagat
7 years ago

Can we disable seekbar control of this you tube player in android?

JavaTechig
JavaTechig
7 years ago
Reply to  Ashish Bhagat

Yes, you can do that using YouTubePlayer.PlayerStyle class.

setPlayerStyle(YouTubePlayer.PlayerStyle style)

player style can be of any of the following

1. YouTubePlayer.PlayerStyle.CHROMELESS- A style that shows no interactive player controls.

2. YouTubePlayer.PlayerStyle.DEFAULT- The default style, showing all interactive controls.

3. YouTubePlayer.PlayerStyle.MINIMAL A minimal style, showing only a time bar and play/pause controls.

Ashish Bhagat
Ashish Bhagat
7 years ago
Reply to  JavaTechig

thank you very much…

JavaTechig
JavaTechig
7 years ago
Reply to  Ashish Bhagat

🙂

john
john
6 years ago
Reply to  JavaTechig

Can we hide or remove youtube logo in player for android

Nilanchala Panigrahy
Nilanchala Panigrahy
6 years ago
Reply to  john

I don’t think so you can do that.. However, I have not explored the new API.

Pushkaraj
Pushkaraj
7 years ago

Hey,

I have a youTubePlayer and some 2-3 different thumbnails. When I play any video it plays for one second and stops. It keeps on happening when I play the video again. But if the video is playing in fullscreen mode, it plays without pausing. The internet connectivity is good.

As part of activity XML, I have created a linear layout which has youTubePlayer . And below that I have added 2 thumbnails with different VIDEO_IDs. When I press on thumbnail, proper video is being played, that is not the issue. The only issue is why is the video stopping (Pausing to be precise) after a second of playback.

Any inputs will really be appreciated.

JavaTechig
JavaTechig
7 years ago
Reply to  Pushkaraj

Are you performing any long running or blocking task?

Seb
Seb
7 years ago
Reply to  Pushkaraj

Same problem for me: the video pauses one second after playing. Any help?

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago

do you mean multiplayer. both side by side?

Krushit Patel
Krushit Patel
7 years ago

yes i do
but now it has been completed

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago

Android key

Arun Badole
Arun Badole
7 years ago

Hi, a very nice tutorial. Can I capture frame (in jpeg or png format) from YouTubePlayerView?

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago
Reply to  Arun Badole

Not quite sure, but as per my knowledge you can’t capture the running frame

Dhiraj Devkar
Dhiraj Devkar
6 years ago

I followed your tutorial but now I got the the error as
an error occured while initialising the you tube player

Harsha Bhagwat
Harsha Bhagwat
6 years ago

Thanks a lot..How do I play video automatically in a stretched view(auto rotated) once I load the activity or on pressing some button??that is it should directly play as shown in the second screenshot of your output.many thanks for any suggestions.

Android Example
Android Example
6 years ago
yann harold
yann harold
6 years ago

hello ! i want to list all channel’s videos in my android app. please help me.

pawandeep Kaur
pawandeep Kaur
6 years ago

hey i want to get core metrics data from youtube please help me

Huy Nguyễn Quốc
Huy Nguyễn Quốc
6 years ago

so you should to remove line ‘ android:padding=”5dp” ‘ in activity_main.xml .

Nikola Brodar
Nikola Brodar
6 years ago

create a listview with pictures. If user click on picture, then it will load, play video for this second picture. This picture is also your thumbail. We can say it that way.

Nikola Brodar
Nikola Brodar
6 years ago

question guys.. how long does your youtube video loads?
For me, for example it takes 4,5,6 second.. and the download speed is 500 KB..
I want to create a youtube, that starts to play after 2,3 second, after buffers just a little data, and start to play. If youtube player buffers just a little data, I want it to play.. Can you please, help me to achieve this?
Thank you a lot 😀

Nikola Brodar
Nikola Brodar
6 years ago

hey guys.. can you please help me.. I would to start playing youtube video, after 2,3 seconds. After youtube makes just a little buffering, I would like to start it playing. Sometimes youtube video plays after 2,3 seconds, sometimes not. I have tried with this example also, but it does not always play after 2,3 seconds.
Especially on android 6.0, or android API 23. There it start to play video after 8, 10, 12, 13 seconds. But sometimes it start to play after 2, 3 seconds. Why is this so?

Nikola Brodar
Nikola Brodar
6 years ago

hey guys.. can you please help me.. I would to start playing youtube video, after 2,3 seconds. After youtube makes just a little buffering, I would like to start it playing. Sometimes youtube video plays after 2,3 seconds, sometimes not. I have tried with this example also, but it does not always play after 2,3 seconds.

Especially on android 6.0, or android API 23. There it start to play video after 8, 10, 12, 13 seconds. But sometimes it start to play after 2, 3 seconds. Why is this so?

Aleksandar Noveski
Aleksandar Noveski
6 years ago

How can I play 3 videos like this in one xml layout?

Paul Hyman
Paul Hyman
5 years ago

Get example. But do you have any example for YouTubePlayerFragement?

Nilanchala Panigrahy
Nilanchala Panigrahy
5 years ago

Unfortunately no. The Android Player API doesn’t have any methods to determine the video playback quality. The video quality is automatically managed by library based on network bandwidth and screen size. However there is no official mention about playback quality.

Nilanchala Panigrahy
Nilanchala Panigrahy
5 years ago
Jeevan Prasad
Jeevan Prasad
5 years ago

comment image

Hi,
I am using again and download Youtubeplayerapi.zip.1.2.2 pest in lib folder after synck but not able to extend youtubebaseactivity .Please help me.So please see my attachment.

Nilanchala Panigrahy
Nilanchala Panigrahy
5 years ago
Reply to  Jeevan Prasad
Bambang Cahyo Soetrisno
Bambang Cahyo Soetrisno
4 years ago

Hi, it’s nice tutorial. I have one question, if i have list of video (dynamic from API) to play and how i can set when video end youtubplayerview autoplay the next video?thanks

Amitabh Bhandari
Amitabh Bhandari
3 years ago

How to add Picture in Picture mode in which only the video enters PIP Mode…

Previous Post

TestFlight to terminate Android support as of March 21

Next Post
genymotion

Genymotion- The Fastest Android Emulator for Application Testing

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
47
0
Would love your thoughts, please comment.x
()
x