How to play Youtube videos in Android Video View?

后端 未结 8 1421
[愿得一人]
[愿得一人] 2020-12-02 14:24

I am developing an android application which requires a youtube video player embedded within it. I successfully got the RTSP video URL from the API, but while trying to load

8条回答
  •  温柔的废话
    2020-12-02 15:01

    Use YouTube Android Player API. It works perfectly. Check my example from here:

    activity_main.xml:

     
    
    
    
    
    

    MainActivity.java:

    package com.example.andreaskonstantakos.vfy;
    
    
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    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 {
    
    YouTubePlayerView youTubePlayerView;
    Button button;
    YouTubePlayer.OnInitializedListener onInitializedListener;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
         youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
         button = (Button) findViewById(R.id.button);
    
    
         onInitializedListener = new YouTubePlayer.OnInitializedListener(){
    
             @Override
             public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
    
                youTubePlayer.loadVideo("Hce74cEAAaE");
    
                 youTubePlayer.play();
         }
    
             @Override
             public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
    
             }
         };
    
        button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
    youTubePlayerView.initialize(PlayerConfig.API_KEY,onInitializedListener);
            }
        });
    }
    }
    

    and the PlayerConfig.java class:

      package com.example.andreaskonstantakos.vfy;
    
    /**
     * Created by Andreas Konstantakos on 13/4/2017.
     */
    
    public class PlayerConfig {
    
    PlayerConfig(){}
    
    public static final String API_KEY = 
    "xxxxx";
    }
    

    Replace the "Hce74cEAAaE" with your video ID from https://www.youtube.com/watch?v=Hce74cEAAaE. Get your API_KEY from Console.developers.google.com and also replace it on the PlayerConfig.API_KEY. For any further information you can follow the following tutorial step by step: https://www.youtube.com/watch?v=3LiubyYpEUk

提交回复
热议问题