Youtube Data API V3 Detailed Methods and Tips
Youtube Data API V3 Detailed Methods and Tips
For Youtube Data Api V3 Creation and Initialization click here
For Youtube Data Api V3 Listeners Tutorial click here
For creating seek to millis(jump to specific location of video) click here
In this post, we will explore everything about Youtube Data Api V3 for android.
Some functionalities we use about Youtube Data API V3
- Youtube player view onError Reason checkup
- Youtube Player view get video length, get current pause time
- Play a list of videos, check next video and autoplay
- Youtube player style
- When to release youtube player
- Some methods get and use it differently. etc.
XML Code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context=".MainActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/youtube_player"/>
<EditText
android:id="@+id/video_seconds"
android:layout_width="87dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Goto"
android:id="@+id/goto_btn"/>
</LinearLayout>
Java Code
package studio.harpreet.sampleyoutubedataapi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView youTubePlayerView;
YouTubePlayer youTubePlayer;
EditText videoSec_et;
Button goto_btn;
MyPlayBackEventListener playBackEventListener;
MyPlayerStateChangeListener playerStateChangeListener;
ArrayList<String> videos = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoSec_et = findViewById(R.id.video_seconds);
goto_btn = findViewById(R.id.goto_btn);
youTubePlayerView = findViewById(R.id.youtube_player);
youTubePlayerView.initialize(getString(R.string.youtube_api_key),this);
playerStateChangeListener = new MyPlayerStateChangeListener();
playBackEventListener = new MyPlayBackEventListener();
goto_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int videolength = youTubePlayer.getDurationMillis()/1000;
int seconds = Integer.parseInt(videoSec_et.getText().toString().trim());
if(seconds < videolength)
{
youTubePlayer.seekToMillis(seconds*1000);
}
else
{
showMessage("Value greater than Video Length");
}
}
});
videos.add("M4q7m7aXqRQ"); // 0
videos.add("t-zoLja8Zlk"); // 1
videos.add("PVH-IHNqDG0");
videos.add("-_pacR6syDo"); // 3 // ths video plays in load videos index
videos.add("uZZ74_y-Jss");
videos.add("C9ptmsoIIaY");
videos.add("V8UGaTiA81w");
videos.add("lZ_QmkWsBBg");
videos.add("JVf1KzMB59k");
videos.add("grR9xC6wyi0");
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
this.youTubePlayer = youTubePlayer;
youTubePlayer.setPlaybackEventListener(playBackEventListener);
youTubePlayer.setPlayerStateChangeListener(playerStateChangeListener);
if(!b)
{
youTubePlayer.cueVideo("-_pacR6syDo",200000); //https://www.youtube.com/watch?v=-_pacR6syDo // plays at 200 sec 200*1000
//youTubePlayer.cueVideos(videos,3,0); // method used as arraylist,index of array list,milliseconds of video start // you can use less or full method
// youTubePlayer.loadVideos(videos,3,0); // method used as arraylist,index of array list,milliseconds of video start // you can use less or full method
// cuevideos is used to only load videos but not play
// load videos is used to load and play
}
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT); // It is set by default if you don't set even
//youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL); // Showing only a time bar and play/pause controls
//youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS); // no interactive controls shown // with this you can play video without interation of user
//let's see all
//youTubePlayer.setManageAudioFocus(false);
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, 1).show();
} else {
String error = String.format("Error initializing YouTube Player ", youTubeInitializationResult.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1)
{
getYoutubePlayerProvider().initialize(getString(R.string.youtube_api_key),this);
}
}
private YouTubePlayer.Provider getYoutubePlayerProvider() {
return youTubePlayerView;
}
private final class MyPlayBackEventListener implements YouTubePlayer.PlaybackEventListener
{
@Override
public void onPlaying() {
showMessage("onPlaying");
Log.d(TAG, "onPlaying: "+ youTubePlayer.getCurrentTimeMillis());
}
@Override
public void onPaused() {
showMessage("OnPaused");
youTubePlayer.getCurrentTimeMillis(); // tells us our video time where it is paused milliseconds 1 sec = 1000 milli seconds
}
@Override
public void onStopped() {
showMessage("OnStopped");
}
@Override
public void onBuffering(boolean b) {
showMessage("onBuffering");
}
@Override
public void onSeekTo(int i) {
showMessage("onSeekTo");
Log.d(TAG, "onSeekTo: "+ youTubePlayer.getCurrentTimeMillis());
}
}
private final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener
{
@Override
public void onLoading() {
showMessage("onLoading");
}
@Override
public void onLoaded(String s) {
showMessage("onLoaded");
youTubePlayer.getDurationMillis(); // returns the value of whole video length in milliseconds 1 sec = 1000 milli seconds
// youTubePlayer.play(); // start playing the video
}
@Override
public void onAdStarted() {
showMessage("onAdStarted");
}
@Override
public void onVideoStarted() {
showMessage("onVideoStarted");
}
@Override
public void onVideoEnded() {
showMessage("onVideoEnded");
if(youTubePlayer.hasNext())
{
youTubePlayer.play();
}
else {
showMessage("last Video Played");
}
}
@Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
if(errorReason.equals(YouTubePlayer.ErrorReason.NETWORK_ERROR)) // unauthorized overlay, when some activity or norification covers the player
{
showMessage("Check Your Internet Connection");
}
//showMessage("onError: "+errorReason);
}
}
private final class MyPlaylistEventListener implements YouTubePlayer.PlaylistEventListener // used only when we play a playlist
{
@Override
public void onPrevious() {
}
@Override
public void onNext() {
}
@Override
public void onPlaylistEnded() {
}
}
private void showMessage(String message)
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
if(youTubePlayer != null)
{
youTubePlayer.release(); // release all functionality of youtube player ,
// needs to initialize again if you want to play video in player
}
}
}
Subscribe to Harpreet studio on Youtube
Like Harpreet Studio on Facebook
Follow me on Instagram
They delivered creative and elegant work. Their workflow was smooth and their design intuition was solid.UI company
ReplyDeleteThey provided honest and insightful feedback that optimized the partnership and project objectives.app design agencies
ReplyDeleteThe complete blogs are really inconceivable and definitely everyone will share this information.
ReplyDeletetop web design companies
I sent your articles links to all my contacts and they all adore it including me.
ReplyDeletebest web design firms
Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks YT Trend
ReplyDeletetwitter
ReplyDelete