【问题标题】:How to use youtube API?如何使用 YouTube API?
【发布时间】:2016-04-25 04:16:01
【问题描述】:

我的班级:

             public class MainActivity_For_Youtube extend YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {

private static final int RECOVERY_DIALOG_REQUEST = 1;
private YouTubePlayerView playerView;
String fbid="";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Called to modify the window feature and resize to full screen
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.youtubevideo);

     fbid = getIntent().getStringExtra("urls");

    playerView = (YouTubePlayerView) findViewById(R.id.player_view);

    // initializes the YouTube player view
    playerView.initialize(Config.API_KEY, this);
}


// Called when YouTube Player initialization is failed
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
                                    YouTubeInitializationResult errorResult) {

    // shows dialog if user interaction may fix the error
    if (errorResult.isUserRecoverableError()) {
        errorResult.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
    }
    else {
        // displays the error occured during the initialization
        String error = String.format(
                getString(R.string.error_string), errorResult.toString());
        Toast.makeText(this, error, Toast.LENGTH_LONG).show();
    }
}


/**
 * Called when initialization of Player is successful
 * @param provider Provider used to initialize the Player
 * @param player Player instance used to control the video playback
 * @param wasRestored Depicts whether the video is restored from a previous
 *                    state. Returns true if video is resumed from the last
 *                    paused state, else returns false
 */
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                    YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {

        player.cueVideo("_oEA18Y8gM0");
        player.setPlayerStyle(PlayerStyle.DEFAULT);
    }
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RECOVERY_DIALOG_REQUEST) {

        // initializes the YouTube player view
        getYouTubePlayerProvider().initialize(Config.API_KEY, this);
    }
}


// Returns Player view defined in xml file
private YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerView) findViewById(R.id.player_view);
}


/**
 * 
 */
private final class EventListener implements YouTubePlayer.PlaybackEventListener {


    /**
     * Called when video starts playing
     */
    @Override
    public void onPlaying() {
        Log.e("Status", "Playing");
    }


    /**
     * Called when video stops playing
     */
    @Override
    public void onPaused() {
        Log.e("Status", "Paused");
    }


    /**
     * Called when video stopped for a reason other than paused
     */
    @Override
    public void onStopped() {
        Log.e("Status", "Stopped");
    }


    /**
     * Called when buffering of video starts or ends
     * @param b True if buffering is on, else false
     */
    @Override
    public void onBuffering(boolean b) {
    }


    /**
     * Called when jump in video happens. Reason can be either user scrubbing
     * or seek method is called explicitely
     * @param i
     */
    @Override
    public void onSeekTo(int i) {
    }
}

private final class StateChangeListener implements YouTubePlayer.PlayerStateChangeListener {

    /**
     * Called when player begins loading a video. During this duration, player
     * won't accept any command that may affect the video playback
     */
    @Override
    public void onLoading() {
    }

    /**
     * Called when video is loaded. After this player can accept
     * the playback affecting commands
     * @param s Video Id String
     */
    @Override
    public void onLoaded(String s) {
    }


    /**
     * Called when YouTube ad is started
     */
    @Override
    public void onAdStarted() {
    }


    /**
     * Called when video starts playing
     */
    @Override
    public void onVideoStarted() {
    }


    /**
     * Called when video is ended
     */
    @Override
    public void onVideoEnded() {
    }


    /**
     * Called when any kind of error occurs
     * @param errorReason Error string showing the reason behind it
     */
    @Override
    public void onError(YouTubePlayer.ErrorReason errorReason) {
    }
}

}

*我已经拿到了android key。我做的一件事是更新到android studio 2.0。 * 我已在https://console.developers.google.com/apis/library?project=alien-vim-***** 上注册,还启用了 youtube 数据 API。生成了 sha-1 并获得了 android 密钥。

得到这些错误:

            Error creating YouTubePlayerView  
          com.google.android.youtube.player.internal.w$a: Exception thrown by invoked
      constructor in com.google.android.youtube.api.jar.client.RemoteEmbeddedPlayer 

            Caused by: java.lang.reflect.InvocationTargetException
             Caused by: java.lang.IllegalArgumentException: The concrete class implementing IObjectWrapper must have exactly *one* declared private field for the wrapped object.  Preferably, this is an instance of the ObjectWrapper<T> class.
            Caused by: java.lang.IllegalArgumentException: The concrete class implementing IObjectWrapper must have exactly *one* declared private field for the wrapped object.  Preferably, this is an instance of the ObjectWrapper<T> class. 

【问题讨论】:

标签: android youtube-api


【解决方案1】:

这是简单的代码,播放视频:

public class PlayVideo extends YouTubeBaseActivity implements
        YouTubePlayer.OnInitializedListener {
    private YouTubePlayer YPlayer;
    private static final String YoutubeDeveloperKey = "Your Key";
    private static final int RECOVERY_DIALOG_REQUEST = 1;

    //String film = "http://www.youtube.com/watch?v=0C0pk9fAhwA";
    public static final String VIDEO_ID = "0C0pk9fAhwA";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layoutplayyoutube);


        YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
        youTubeView.initialize(YoutubeDeveloperKey, this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider,
            YouTubeInitializationResult errorReason) {
        if (errorReason.isUserRecoverableError()) {
            errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
        } else {
            String errorMessage = String.format(
                    "There was an error initializing the YouTubePlayer",
                    errorReason.toString());
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onInitializationSuccess(Provider provider,
            YouTubePlayer player, boolean wasRestored) {
        if (!wasRestored) {
            YPlayer = player;
            /*
             * Now that this variable YPlayer is global you can access it
             * throughout the activity, and perform all the player actions like
             * play, pause and seeking to a position by code.
             */
            YPlayer.cueVideo(VIDEO_ID);
        }
    }
}

布局.xml:

<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".PlayVideo" >

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

【讨论】:

  • 第一次播放视频但之后收到错误消息..@D T
猜你喜欢
  • 2015-07-29
  • 1970-01-01
  • 2020-02-22
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
  • 2012-12-09
  • 1970-01-01
相关资源
最近更新 更多