android - 无法加载多个YouTube视频

时间:2018-01-02 05:14:01

标签: java android android-fragments video youtube

我需要在同一活动中使用“YouTubePlayer”多个实例播放多个“youtube”视频。换句话说,我需要像YouTube应用程序如何在另一个下方显示不同的视频一样。我使用'FrameLayout'插入'YouTubePlayerFragment'。在我的情况下,多个“YouTubePlayer”实例正在加载相同的YouTube视频,即使我提供了不同的视频ID。

请检查以下代码

activity_main.xml中

<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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

                <FrameLayout
                android:id="@+id/youtube_fragment"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:layout_centerHorizontal="true"
                android:visibility="visible" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="20dp"
                    android:orientation="vertical">

                </LinearLayout>

                <FrameLayout
                    android:id="@+id/youtube_fragment1"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_centerHorizontal="true"
                   android:visibility="visible" />                        

            </LinearLayout>      
        </ScrollView>      

    </LinearLayout>

MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
import com.google.android.youtube.player.YouTubePlayerView;

public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {

    private static final int RECOVERY_REQUEST = 1;
    private YouTubePlayerView youTubeView, youTubeView1;
    private YouTubePlayerFragment youTubePlayerFragment, youTubePlayerFragment1;
    private YouTubePlayer youTubePlayer, youTubePlayer1;
    private boolean isFullScreen;
    private int currentTimeMillis;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);   
        YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
        youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);

        YouTubePlayerSupportFragment youTubePlayerFragment1 = YouTubePlayerSupportFragment.newInstance();
        youTubePlayerFragment1.initialize(Config.YOUTUBE_API_KEY, this);    
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit();    
        FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
        transaction1.add(R.id.youtube_fragment1, youTubePlayerFragment1).commit();

    }

    @Override
    public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {

            this.youTubePlayer = player;
            this.youTubePlayer.cueVideo("cumrdTrE7J0"); 
            youTubePlayer.seekToMillis(30000);    
            this.youTubePlayer1 = player;
            this.youTubePlayer1.cueVideo("QQ3ki1dCcnw"); 
            youTubePlayer1.seekToMillis(30000);    
            this.youTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
                @Override
                public void onFullscreen(boolean b) {
                    isFullScreen = b;

                }
            });    
            this.youTubePlayer1.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
                @Override
                public void onFullscreen(boolean b) {
                    isFullScreen = b;   
                }
            });

        this.youTubePlayer.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
            @Override
            public void onPlaying() {    
            }    
            @Override
            public void onPaused() {
                Toast.makeText(MainActivity.this,"Pause",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onStopped() {
                Log.d("MainActivity_1","onStopped()");
                currentTimeMillis = youTubePlayer.getCurrentTimeMillis();
                Log.d("MainActivity_1","Current Time Millis: "+currentTimeMillis);

            }    
            @Override
            public void onBuffering(boolean b) {
                Log.d("MainActivity_1","onBuffering()");
            }

            @Override
            public void onSeekTo(int i) {

            }
        });    
        this.youTubePlayer1.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
            @Override
            public void onPlaying() {    
            }    
            @Override
            public void onPaused() {
                Toast.makeText(MainActivity.this,"Pause",Toast.LENGTH_LONG).show();
            }
                @Override
            public void onStopped() {
                Log.d("MainActivity_1","onStopped()");
                currentTimeMillis = youTubePlayer1.getCurrentTimeMillis();
                Log.d("MainActivity_1","Current Time Millis: "+currentTimeMillis);

            }    
            @Override
            public void onBuffering(boolean b) {
                Log.d("MainActivity_1","onBuffering()");
            }

            @Override
            public void onSeekTo(int i) {

            }
        });

    }

    @Override
    public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
        if (errorReason.isUserRecoverableError()) {
            errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
        } else {
            String error = String.format(getString(R.string.player_error), errorReason.toString());
            Toast.makeText(this, error, Toast.LENGTH_LONG).show();
        }
    }    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECOVERY_REQUEST) {
            // Retry initialization if user performed a recovery action
            getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
            getYouTubePlayerProvider1().initialize(Config.YOUTUBE_API_KEY, this);

        }
    }    
    protected Provider getYouTubePlayerProvider() {
        return youTubeView;
    }

    protected Provider getYouTubePlayerProvider1() {
        return youTubeView1;
    }       
    @Override
    public void onBackPressed() {


        if(isFullScreen)
        {                
           youTubePlayer.setFullscreen(false);
            youTubePlayer1.setFullscreen(false);
        }
        else
        {
            //Toast.makeText(this,"Not Full Screen",Toast.LENGTH_LONG).show();
            super.onBackPressed();
        }
    }
}

Config.java

public final class Config {

    private Config() {
    }    
    public static final String YOUTUBE_API_KEY = "AIzaSyA2HhbLUS6I2f01moTj8YJGosPzGZ3VZaw";    

}

的build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.graphs.youtubeapitext"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}    
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
    compile files('libs/YouTubeAndroidPlayerApi.jar')
}

如何在不同时播放不同的YouTube视频,而不是每次都重复播放相同的视频?

P.S:在我的真实应用程序中,我将使用Fragments而不是Activities。

1 个答案:

答案 0 :(得分:0)

您无法为解决方案创建YouTubePlayerFragment的多个实例,

首先,显示YouTube视频here

的缩略图

点击该缩略图后,发布YouTubePlayerFragment(如果有任何已经过主题化的内容),并根据点击的缩略图在YouTubePlayerFragmentR.id.youtube_fragment添加新的R.id.youtube_fragment1

发布YouTubePlayerFragment

mYoutubePlayer.release();

添加新

YouTubePlayerSupportFragment youTubePlayerFragment1 = YouTubePlayerSupportFragment.newInstance();
        youTubePlayerFragment1.initialize(Config.YOUTUBE_API_KEY, this);    
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.youtube_fragment, youTubePlayerFragment).commit();

如果有视频列表,您也可以使用RecyclerView