How To Play Youtube In Android Studio
Hello guys, on this occasion I will show you how to add Youtube Player on Android Studio.
This tutorial is very useful for those of you who have a youtube channel and want to show your videos to other platforms such as applications, web and so on.
But before that you must have an "API" as shown below.
Now, we download the Youtube Player library here
If it's been downloaded, ekstract all files in the app folder in your project
in the libs folder, there is a .jar file that we enter into dependencies
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile files('libs/YouTubeAndroidPlayerApi.jar')
}
When finished, open activity_main.xml and enter the following code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#000"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/youtube_player_view"
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Now, open MainActivity.java then enter the following code
import android.os.Bundle;
import android.widget.Button;
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.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView youTubePlayerView;
Button btn;
public static final String API_KEY = "YOUR-API-KEY";
//www.youtube.com/watch?v=OTOku-K_ORk
//id video "OTOku-K_ORk"
String VIDEO_ID = "YOUR-ID-VIDEO";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player_view);
youTubePlayerView.initialize(API_KEY,this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if(null== player) return;
// Start buffering
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(this, "Failed to initialize.", Toast.LENGTH_LONG).show();
}
}
And the last enter the permission in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
When it's finished, run the program and the results are more or less like the picture below