Android: Create YouTube Player

Android: Create YouTube Player

Let's leave Android TV project for a while. I want to put some YouTube videos on a regular app. Here are some requirements for you to play YouTube files:

1, API key. 2, YouTube Android API.

Simple, let's code.

#1, New Project

You can open a new empty project in Android Studio 3. Let's call it, YoutubeDataDemo. The package name is,

package name: com + your name + project name

Example: com.huang.homan.youtubedatademo

This is important because we will use this package name in our API file.

#2, API key

Go to Google Developer Console, you need to add a new project. Let's use a same name, YouTube Data Demo.





Next, you need to enable the API service. Follow the steps until you reach

CREATE CREDENTIALS.




Let's create restrict key for Android only.




Go to Android Studio, you need to get package name and SHA1 fingerprint.



Your key is ready.


#3, Create Key Config

In Android Studio, let's add a YouTubeKeyConfig.java.

Copy and paste the new key into the string variable.



#4, YouTube Android Player API

To play YouTube video, you also need YouTube Android Player API.


Unzip the library file to app/libs.



Add the new file to build.gradle.

dependencies {  
    ...  
 
    //Youtube Player  
    implementation files('libs/YouTubeAndroidPlayerApi.jar')  
}
#5, UI: YouTubePlayerView

Let's code the UI. You need to open activity_main.xml. Let's give a name, youtubeCL, to primary layout.


Drop a view of container into youtubeCL called youtubePlayerView.





#6, UI: Play button


Let's add a play button.

Called playBT.




#7, MainActiviy

Let's add some UI variables:

public class MainActivity extends AppCompatActivity {

    YouTubePlayerView youTubePlayerView;
    Button playBT;

You need YouTubePlayer.OnInitializedListener to play. Let's add one.

YouTubePlayer.OnInitializedListener mYouTubeOnlistener;

Intialize them in onCreate().

//UI
youTubePlayerView = findViewById(R.id.youtubePlayerView);
playBT = findViewById(R.id.playBT);

//Check ON/OFF  
mYouTubeOnlistener = new YouTubePlayer.OnInitializedListener() {
    @Overridepublic void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

    }

    @Overridepublic void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

    }
};

Add click function.

playBT.setOnClickListener(v ->  
        youTubePlayerView.initialize(  
                YouTubeKeyConfig.KEY, //your api key  
                mYouTubeOnlistener)); //your youtube listener  

This is lambda version. Please update the build.gradle with lambda option.

android {  
    ...
    compileOptions {  
        sourceCompatibility JavaVersion.VERSION_1_8  
        targetCompatibility JavaVersion.VERSION_1_8  
    }  
}
#8, Log

To prepare debug, you need to set some log anchors.

public class MainActivity extends AppCompatActivity {

    /* Log tag and shortcut */  
    final static String TAG = "MYLOG YtPlayer";
    public static void ltag(String message) { Log.i(TAG, message); }

At onCreate(),

@Override  
protected void onCreate(Bundle savedInstanceState) {  
    ...  
 
    ltag("onCreate.");  
 
    ...
  
    playBT.setOnClickListener(v -> {  
        ltag("playBT: Initializing player.");  
        youTubePlayerView.initialize(  
                YouTubeKeyConfig.KEY,  
                mYouTubeOnlistener); 
    });  
 
    //Check ON/OFF  
    mYouTubeOnlistener = new YouTubePlayer.OnInitializedListener() {  
        @Override  
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {  
            ltag("playBT: End initializing.");  
        }  
 
        @Override  
        public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {  
            ltag("playBT: FAILED to initialize player.");  
        }  
    };   
    
}
#9, Play sample

Let's play a sample. Here is the link.

You only need to copy string after v=... to your listener.

//Check ON/OFF  
mYouTubeOnlistener = new YouTubePlayer.OnInitializedListener() {  
    @Override  
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {  
        ltag("playBT: End initializing.");  

        youTubePlayer.loadVideo("0XYWpraTgaY");  
    }

Let's run.

#10, Debug

Oohs, multidex issue:

java.lang.RuntimeException: 
com.android.builder.dexing.DexArchiveMergerException: 
Error while merging dex archives:
The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at 
https://developer.android.com/tools/building/multidex.html

Let's fix build.gradle.

android {  
    compileSdkVersion 28  
    defaultConfig {  
        ...  
        multiDexEnabled true  
        ...
    }  
    buildTypes {  
        release {  
            minifyEnabled false  
            multiDexKeepFile file('multidex-config.txt')  
            multiDexKeepProguard file('multidex-config.pro')  
            ...
        }  
    }  
    ...
}  
 
dependencies {  
    ...  
 
    implementation 'com.android.support:multidex:1.0.3'  
 
}  

Run again.

New error:

Binary XML file line #10: 
Binary XML file line #10: 
Error inflating class com.google.android.youtube.player.YouTubePlayerView

I found the bug is in,

public class MainActivity extends AppCompatActivity {

It should extends

public class MainActivity extends YouTubeBaseActivity {

Problem solved.

You can set style: without control bar.

//Check ON/OFF  
mYouTubeOnlistener = new YouTubePlayer.OnInitializedListener() {
    @Override  
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
        ltag("playBT: End initializing.");

        String videoID = "0XYWpraTgaY";
        youTubePlayer.loadVideo(videoID);
        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
        youTubePlayer.play();
    }

No bar at all.


Thanks for reading! Next, we will put those YouTube video on Android TV.







要查看或添加评论,请登录

Homan Huang的更多文章

社区洞察

其他会员也浏览了