YouTubePlayer.play() not working in android-youtube-player

195 Views Asked by At

So I'm trying to programmatically play a YouTube video using this youtube IFrame wrapper . The video loads successfully and can be played via the default controls on the youtube UI, but the issue is when I try to play the video programmatically (i.e via an external button) then it does nothing. I've stepped through to the library methods and the correct commands (e.g cueVideo, playVideo, pauseVideo) are triggered without any errors, yet the video itself doesn't respond as it should.

I initialize the video as follows:

void loadYouTubeThingy(){
//You can assume that I've done some null checks and other sanity measures not relevant to the question
        YoutubePlayerFragment player = YoutubePlayerFragment.getInstance();
        webView = (YouTubePlayerView) (Object) player.getChildFragmentManager().findFragmentById(R.id.youtube_fragment);

        try {
            YouTubePlayerListener listener = new AbstractYouTubePlayerListener(){};
            IFramePlayerOptions options = new IFramePlayerOptions.Builder().controls(0).build();
            webView.setEnableAutomaticInitialization(false);
            webView.initialize(listener, options);
            webView.getYouTubePlayerWhenReady(youTubePlayer -> {
                //Add a tracker to get various info from the video
                youTubePlayer.addListener(tracker);
                video = Optional.of(youTubePlayer);
            });
        } catch (IllegalStateException e) {
            UnisonMobileLog.e("YoutubePlayerFragment", "Exception initialising youtube webview.", e);
        }
}

And here are some ways in which I tried to call it (video is of youTubePlayer type):

    public void play() {

         video.ifPresent(YouTubePlayer::play);

        //...variation
        if(video != null){         
            video.play();
        }

        //..and another variation
        webView.getYouTubePlayerWhenReady(youTubePlayer -> { 
            youTubePlayer.play();
        });
    }

And just in case, here's how I defined the XML element

    <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
        android:id="@+id/youtube_fragment"
        android:name="com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView"
        android:layout_width="match_parent"
        android:layout_height="241dp"
        app:videoId="@string/yt_test_video_a"
        app:handleNetworkEvents="false"
        android:background="@android:color/black"
        tools:ignore="Instantiatable" />

Like I say, there are no errors, warnings or exceptions and the video works fine when directly using the YouTube UI. Can anyone tell me what I'm missing?

0

There are 0 best solutions below