YouTube Player library for Android and Chromecast, stable and customizable.

Overview

android-youtube-player

Build Status core chromecast-sender android arsenal website

share on twitter

android-youtube-player is a stable and customizable open source YouTube player for Android. It provides a simple View that can be easily integrated in every Activity/Fragment.

To interact with YouTube the library uses the IFrame Player API, inside of a WebView, therefore the YouTube app is not required on the user's device and there are no issues with YouTube Terms of Service.

The web UI of the IFrame Player player is hidden. Instead, a native UI built on top of Android is used to interact with the player, providing a native experience to the users.

The UI of the player is 100% customizable. The default UI can be changed, to show and hide new views, or can be completely replaced by a custom UI.

This library also provides a Chromecast YouTube player, that you can use to cast YouTube videos from your app to a Chromecast device.

Why does this library exist?

The official library provided by Google to integrate YouTube videos in Android apps is the YouTube Android Player API. The official library is quite buggy (some bugs are 5+ years old) and lacks in support from Google. I found it to be quite unreliable and therefore unusable in production.

This, added to its limited options for customization and lack of Chromecast support, lead me to the development of this open source library.

A lengthier explanation to why you may want to consider using an alternative to the official YouTube player is written in this Medium post.


A list of published apps that are using this library: (let me know if you want to add your app to this list)

showcase

Does this library breaks YouTube terms of service?

TL;DR No.

The library uses YouTube's own web player to play videos. Therefore it is 100% compliant with terms of service. You can see here how this is also the official way of playing YouTube videos on iOS.

If you want to be 200% sure to be safe, disable the native UI and enable the web player's built in web UI.

That said how you use the library matters, be sure to play videos only when the player is visible. If you follow the instructions in the documentation, the library will automatically handle this for you.

Also remember when publishing your app on the PlayStore to write title and description in a way that makes it obvious that your app doesn't have any affiliation with YouTube (the company). This is issue has nothing to do with the library itself, but I figured it may be useful knowledge for many of you considering to use it.

Table of Contents (Core)

  1. Sample app
  2. Download
    1. Core
    2. Chromecast
  3. Quick start
  4. API documentation
    1. YouTubePlayerView
      1. XML attributes
      2. Initialization
      3. IFramePlayerOptions
      4. Full screen
      5. UI
      6. Release the YouTubePlayerView
      7. LifecycleObserver
    2. YouTubePlayer
      1. Get a reference to YouTubePlayer
      2. Load videos
        1. Utility for loading videos
      3. Events
      4. YouTubePlayerTracker
    3. YouTubePlayerListener
      1. onReady callback
      2. onStateChanged callback
    4. PlayerUiController
      1. Show video title
      2. Live videos
      3. Custom actions
    5. Create your own custom UI
      1. Reusable UI components
        1. YouTubePlayerSeekBar
        2. FadeViewHelper
        3. TimeUtilities
    6. Web-based UI
    7. Menu
      1. YouTubePlayerMenu
      2. MenuItem
    8. Network events
    9. Chromecast support
    10. Useful info
      1. Hardware acceleration
      2. Play YouTube videos in the background
      3. minSdk
      4. How to disable share and watch later buttons

Table of Contents (Chromecast)

  1. Chromecast extension library
  2. Quick start and API documentation
    1. Download extra dependencies
    2. Sender
    3. Receiver
    4. Registration
    5. Hosting the Chromecast receiver

Sample app

📝 Both the core module and the chromecast module have a sample app, to provide examples of usage of the libraries.

📲 You can also download and install the apks of both sample apps.

👀 If you want to know when a new release of the library is published: watch this repository on GitHub.

Download

The Gradle dependency is available via jCenter. jCenter is the default Maven repository used by Android Studio.

The minimum API level supported by this library is API 17. Also, your app needs to be using the androidx libraries instead of the old support libraries.

Core

The core module contains the YouTube Player. It's all you need to play YouTube videos in your app.

dependencies {
  implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.5'
}

Chromecast

The chromecast-sender module contains the Chromecast YouTube Player. Use it if you need to cast YouTube videos from your app to a Chromecast device.

dependencies {
  implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:chromecast-sender:0.23'
}

Quick start

In order to start using the player you need to add a YouTubePlayerView to your layout.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
        android:id="@+id/youtube_player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        
        app:videoId="S0Q4gqBUs7c"
        app:autoPlay="true"
        app:showFullScreenButton="false" />
</LinearLayout>

It is recommended that you add YouTubePlayerView as a lifecycle observer of its parent Activity/Fragment. You can read why in the documentation.

YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player_view);
getLifecycle().addObserver(youTubePlayerView);

(If you have problems adding YouTubePlayerView as a LifecycleObserver, you probably aren't using androidx, I suggest you migrate your dependencies)

That's all you need, a YouTube video is now playing in your app.

If you want more control, everything can be done programmatically by getting a reference to your YouTubePlayerView and adding a YouTubePlayerListener to it.

YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player_view);
getLifecycle().addObserver(youTubePlayerView);

youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
  @Override
  public void onReady(@NonNull YouTubePlayer youTubePlayer) {
    String videoId = "S0Q4gqBUs7c";
    youTubePlayer.loadVideo(videoId, 0);
  }
});

API documentation

The following sections provide detailed documentation for every component of the library.

If you see any problem or mistake in the documentation, feel free to contribute by opening an issue an/or sending a pull request.

YouTubePlayerView

YouTubePlayerView is the access point to the YouTubePlayer.

You can add the View to your layout.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
        android:id="@+id/youtube_player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Or you can create it programmatically and manually add it to a ViewGroup.

YouTubePlayerView youTubePlayerView = new YouTubePlayerView(this);
layout.addView(youTubePlayerView);

If the height of the View is set to wrap_content, the View will automatically have an aspect ratio of 16:9, to match the aspect ratio of most YouTube videos.

XML attributes

If you add the view to your XML layout you have the possibility to set a few custom attributes, to customize the view's look and behavior. Everything can also be done programmatically.

videoId

This attribute expects a String, which is the id of a YouTube video.

If set, the player will automatically start playing the video.

If not set, the player won't automatically play.

In general you should use this attribute if you want your player to play only one video. This is not a rule, just best practice. In fact, even if you set the attribute it is still possible to play other videos programatically.

autoPlay

This attribute expects a boolean. Its default value is false.

If true, the player start playing the video provided with videoId without waiting for user input.

If false, the player will wait for user input before playing the video provided with videoId.

If videoId is not set, this attribute is useless, therefore if it is set to true YouTubePlayerView will throw an exception.

autoPlay won't work if YouTubePlayerView is not added as a LifecycleObserver of its parent Activity/Fragment.

enableAutomaticInitialization

This attribute expects a boolean. Its default value is true.

If true, YouTubePlayerView will take care of its initialization.

If false, you will have to initialize YouTubePlayerView programmatically.

In general it makes sense to leave this attribute to true. You may want to set it to false only if you need to initialize the view using IFramePlayerOptions.

handleNetworkEvents

This attribute expects a boolean. Its default value is true.

If true, YouTubePlayerView handle network events by registering a NetworkReceiver.

If false, you will be responsible for handling network events.

It is useful to have this attribute set to true so that if the connection drops while the player is initializing YouTubePlayerView will be able to resume the initialization automatically once the network is back.

If you decide to set it to false you should also disable enableAutomaticInitialization and manage network events on your own.

Read more about network events here.

useWebUi

This attribute expects a boolean. Its default value is false.

If true, YouTubePlayerView will use the web-based UI of the IFrame YouTubePlayer.

If false, YouTubePlayerView will use the native UI of the library.

YouTube added some non-removable buttons to the IFrame Player, as mentioned in this issue. Using the web-based UI is the only way to have access to these non-removable buttons.

Read the documentation of the initializeWithWebUi method to learn more about the effects of this attribute.

Web UI screenshot:

web-ui screenshot

enableLiveVideoUi

This attribute expects a boolean. Its default value is false.

If true, YouTubePlayerView will use UI for live videos.

If false, YouTubePlayerView will use the UI normal videos.

This attribute does nothing if useWebUi is true.

Live UI screenshot:

live-ui screenshot

showYouTubeButton

This attribute expects a boolean. Its default value is true.

If true, YouTubePlayerView will show a small clickable YouTube icon in the lower right corner of the player.

If false, YouTubePlayerView will not show a small clickable YouTube icon in the lower right corner of the player.

This attribute does nothing if useWebUi is true.

showFullScreenButton

This attribute expects a boolean. Its default value is true.

If true, YouTubePlayerView will show a button to enter and exit full-screen.

If false, YouTubePlayerView will not show a button to enter and exit full-screen.

This attribute does nothing if useWebUi is true.

showVideoCurrentTime

This attribute expects a boolean. Its default value is true.

If true, YouTubePlayerView will show the current time of the current video.

If false, YouTubePlayerView will not show the current time of the current video.

This attribute does nothing if useWebUi is true.

showVideoDuration

This attribute expects a boolean. Its default value is true.

If true, YouTubePlayerView will show the time duration of the current video.

If false, YouTubePlayerView will not show the time duration of the current video.

This attribute does nothing if useWebUi is true.

showSeekBar

This attribute expects a boolean. Its default value is true.

If true, YouTubePlayerView will show a SeekBar to control video playback.

If false, YouTubePlayerView will not show a SeekBar to control video playback.

This attribute does nothing if useWebUi is true.

Initialization

If you need to initialize YouTubePlayerView programmatically, you can set its xml attribute enableAutomaticInitialization to false. You can do the same programmatically by calling youTubePlayerView.setEnableAutomaticInitialization(false).

After automatic initialization has been disabled, you need to take care of the initialization of YouTubePlayerView.

You can use these methods:

YouTubePlayerView.initialize(YouTubePlayerListener listener)
YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents)
YouTubePlayerView.initializeWithWebUi(YouTubePlayerListener listener, boolean handleNetworkEvents)
YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents, IFramePlayerOptions iframePlayerOptions)

initialize(YouTubePlayerListener)

Initialize the YouTubePlayer. Network events are automatically handled by the player.

The argument is a YouTubePlayerListener, you can read more about it here.

initialize(YouTubePlayerListener, boolean)

Initialize the YouTubePlayer. By using the boolean is possible to decide if the player should handle network events or not, read more about network events here.

initialize(YouTubePlayerListener, boolean, IFramePlayerOptions)

By passing an IFramePlayerOptions to the initialize method it is possible to set some of the parameters of the IFrame YouTubePlayer. Read more about IFramePlayerOptions here.

All the possible parameters and values are listed here. Not all of them are supported in this library because some don't make sense in this context. Open an issue if you need a parameter that is not currently supported.

initializeWithWebUi(YouTubePlayerListener, boolean)

This method is identical to initialize(YouTubePlayerListener, boolean) but it disables the native UI of the player and instead uses the web-based UI of the IFrame Player API.

Because the native UI is disabled trying to call YouTubePlayerView.getPlayerUiController() will throw an exception.

YouTube added some non-removable buttons to the IFrame Player, as mentioned in this issue. Using the web-based UI is the only way to have access to these non-removable buttons.

IFramePlayerOptions

The IFramePlayerOptions is an optional argument that can be passed to YouTubePlayerView.initialize(YouTubePlayerListener, boolean, IFramePlayerOptions), it can be used to set some of the parameters of the IFrame YouTubePlayer.

A simple example of how to use IFramePlayerOptions can be found in the sample app here.

Use the Builder to get a IFramePlayerOptions object.

IFramePlayerOptions iFramePlayerOptions = new IFramePlayerOptions.Builder()
  .controls(1)
  .build();

All the possible parameters and values are listed here. Not all of them are supported in this library because some don't make sense in this context. Open an issue if you need a parameter that is not currently supported.

Supported options

controls

This option indicates whether the web-based UI of the IFrame player should be hidden or visible.

If set to 0: web UI is not visible.

If set to 1: web UI is visible.

rel

This option controls the related videos shown at the end of a video.

If set to 0: related videos will come from the same channel as the video that was just played.

If set to 1: related videos will come from multiple channels.

ivLoadPolicy

This option controls video annotations.

If set to 1: the player will show annotations.

If set to 3: the player won't show annotations.

ccLoadPolicy

This option controls video captions. It doesn't work with automatically generated captions.

If set to 0: the player will show captions.

If set to 1: the player won't show captions.

Full screen

You can use the YouTubePlayerView to enter and exit full-screen.

youTubePlayerView.enterFullScreen();
youTubePlayerView.exitFullScreen();
youTubePlayerView.isFullScreen();
youTubePlayerView.toggleFullScreen();

You can also add listeners to get notified when the YouTubePlayerView enters or exits full-screen.

youTubePlayerView.addFullScreenListener(YouTubePlayerFullScreenListener fullScreenListener);
youTubePlayerView.removeFullScreenListener(YouTubePlayerFullScreenListener fullScreenListener);

enterFullScreen() and exitFullScreen() will:

  • set YouTubePlayerView's height and width to MATCH_PARENT
  • update the UI of the player to match the new state. (eg: update the full-screen button)

It is responsibility of the developer to hide other Views in the Activity, change the orientation of the Activity etc. The sample app contains an helper class that can help you to update your app state, but this is not part of the library.

If you need to change the orientation of your Activity/Fragment, remember that by default Android recreates Activities and Fragments when the orientation changes. Make sure that you manually handle orientation changes by adding the attribute android:configChanges to your Activity definition in the manifest.

<application >
  <activity
    android:configChanges="orientation|screenSize|keyboardHidden|smallestScreenSize|screenLayout" />
</application>

UI

If you want to interact with the UI of the player you need to get a reference to the PlayerUiController from the YouTubePlayerView by calling this method

PlayerUiController YouTubePlayerView.getPlayerUiController();

Read the documentation of PlayerUiController.

Release the YouTubePlayerView

Remember to release the YouTubePlayerView when you're done using it, by calling YouTubePlayerView.release().

@Override
public void onDestroy() {
    super.onDestroy();
    youTubePlayerView.release();
}

You don't need to manually release the player if you registered it as an observer of your Activity/Fragment's lifecycle.

LifecycleObserver

YouTubePlayerView implements the LifecycleObserver interface, this means that it is a lifecycle aware component.

If added as an observer of your Activity/Fragment's lifecycle, YouTubePlayerView will be smarter. It is highly recommended that you register YouTubePlayerView as a LifecycleObserver.

lifecycleOwner.getLifecycle().addObserver(youTubePlayerView);

Adding YouTubePlayerView as an observer to a lifecycle will allow YouTubePlayerView to automatically pause the playback when the Activity/Fragment stops (not when it pauses, in order to support multi-window applications).

If you want your app to keep playing when the Activity/Fragment is not visible (remember that this behavior is not allowed, if you want to publish your app on the PlayStore), don't register the YouTubePlayerView as a lifecycle observer. But remember to manually call release() when the Activity/Fragment is being destroyed.

YouTubePlayer

YouTubePlayer is the component responsible for controlling the playback of YouTube videos. You can see its contract here.

Every YouTubePlayerView contains a YouTubePlayer.

Get a reference to YouTubePlayer

There are two ways to get a reference to the YouTubePlayer, through the YouTubePlayerView.

1. YouTubePlayerView.getYouTubePlayerWhenReady

YouTubePlayerView.getYouTubePlayerWhenReady can be used to get a reference to the YouTubePlayer. As the name of the method says, you'll only get the player when it is ready.

Therefore this function takes a callback as argument, the callback will be called when the YouTubePlayer is ready.

youTubePlayerView.getYouTubePlayerWhenReady(youTubePlayer -> { 
  // do stuff with it
})

2. YouTubePlayerListener

Every method of a YouTubePlayerListener has the YouTubePlayer as argument.

Load videos

To load a video you can use two methods.

YouTubePlayer.loadVideo(String videoId, float startTime)

or

YouTubePlayer.cueVideo(String videoId, float startTime)

The difference between the two is that loadVideo loads and automatically plays the video, while cueVideo just loads video and thumbnail but doesn't autoplay.

Utility for loading videos

If the Activity/Fragment is in the background, but you created a YouTubePlayerListener that calls loadVideo when onReady is called, the video will start playing even if the Activity is in the background.

To solve this problem you should use the loadOrCueVideo function.

Provided as an utility function in Java.

YouTubePlayerUtils.loadOrCueVideo(
  youTubePlayer,
  getLifecycle(),
  videoId,
  startTime
);

And as an extension function in Kotlin.

youTubePlayer.loadOrCueVideo(lifeCycle, videoId, startTime)

This function will call loadVideo only if the Activity is resumed, otherwise it will call cueVideo, so that the video starts loading but not playing.

Events

During its existence the player will constantly emit events, you can easily listen to all of them by adding a YouTubePlayerListener to it.

YouTubePlayerTracker

YouTubePlayerTracker is an utility provided by the library to easily keep track of a YouTubePlayer's state and other information.

YouTubePlayerTracker is a YouTubePlayerListener, therefore in order to use it you need to add it as a listener to the YouTubePlayer.

You can then use the tracker to get the player's state and various information about the video that is being played.

YouTubePlayerTracker tracker = new YouTubePlayerTracker();
youTubePlayer.addListener(tracker);

tracker.getState();
tracker.getCurrentSecond();
tracker.getVideoDuration();
tracker.getVideoId();

YouTubePlayerListener

A YouTubePlayerListener is used to intercept events emitted by a YouTubePlayer.

During its existence a YouTubePlayer will constantly emit events, you can listen to them by adding a YouTubePlayerListener to it.

youTubePlayer.addListener(YouTubePlayerListener listener);
youTubePlayer.removeListener(YouTubePlayerListener listener);

These are the method that a YouTubePlayerListener must implement, every method takes a reference to the YouTubePlayer and some other arguments.

// Called when the player is ready to play videos.
// You should start using the player only after this method is called.
void onReady(@NonNull YouTubePlayer youTubePlayer)

// Called every time the state of the player changes.
void onStateChange(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlayerState state)

// Called every time the quality of the playback changes.
void onPlaybackQualityChange(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlaybackQuality playbackQuality)

// Called every time the speed of the playback changes.
void onPlaybackRateChange(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlaybackRate playbackRate)

// Called when an error occurs in the player.
void onError(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlayerError error)

// Called periodically by the player, the argument is the number of seconds that have been played.
void onCurrentSecond(@NonNull YouTubePlayer youTubePlayer, float second)

// Called when the total duration of the video is loaded.
// Note that getDuration() will return 0 until the video's metadata is loaded, which normally happens just after the video starts playing.
void onVideoDuration(@NonNull YouTubePlayer youTubePlayer, float duration)

// Called periodically by the player, the argument is the percentage of the video that has been buffered.
void onVideoLoadedFraction(@NonNull YouTubePlayer youTubePlayer, float loadedFraction)

// Called when the id of the current video is loaded
void onVideoId(@NonNull YouTubePlayer youTubePlayer, String videoId)

void onApiChange(@NonNull YouTubePlayer youTubePlayer)

If you don't want to implement all the methods of this interface, you can extend AbstractYouTubePlayerListener instead of implementing YouTubePlayerListener and override only the methods you are interested in.

For more information on the methods defined in the YouTubePlayerListener interface, please refer to the documentation defined above each method in the codebase.

onReady callback

The onReady callback of a YouTubePlayerListener is called once, when the YouTubePlayer is ready to be used for the first time. You can't use a YouTubePlayer before it is ready.

onStateChanged callback

The YouTubePlayer has a state, that changes accordingly to the playback changes. The list of possible states is the same of the YouTube IFrame Player API.

UNKNOWN
UNSTARTED
ENDED
PLAYING
PAUSED
BUFFERING
VIDEO_CUED

PlayerUiController

The PlayerUiController is responsible for controlling the UI of a YouTubePlayerView.

You can get a reference to the PlayerUiController from the YouTubePlayerView

youTubePlayerView.getPlayerUiController();

PlayerUiController offers a lot of method to control the UI, only a few of them are presented in the following sections.

Show video title

Due to changes to the IFrame API, the web-based IFrame player will always show the title of the video.

Nevertheless, the PlayerUiController exposes a method called setVideoTitle(String videoTitle) that can be used to set the title on the Android side (unfortunately setting this title won't remove the title from the WebView).

Live videos

If you want to play live videos you must setup the UI accordingly, by calling this method.

PlayerUiController.enableLiveVideoUi(boolean enable);

Unfortunately there is no way for the player to automatically know if it is playing a live video or not, therefore is up to the developer to change the UI.

You can obtain the same result by setting the xml attribute app:enableLiveVideoUi="true" of YouTubePlayerView.

Live-ui screenshot:

live-ui screenshot

Custom actions

You can set custom actions on the right and left side of the Play/Pause button of the player

PlayerUiController.setCustomAction1(Drawable icon, OnClickListener listener);
PlayerUiController.setCustomAction2(Drawable icon, OnClickListener listener);
PlayerUiController.showCustomAction1(boolean show);
PlayerUiController.showCustomAction2(boolean show);

Custom actions example:

custom actions screenshot

You can also add any type of View to the UI, this can be useful if you want to add a new icon.

PlayerUiController.addView(View view);
PlayerUiController.removeView(View view);

The View will be added to the top corner of the player.

Example of views added to the player (see Chromecast icon in the top-right corner):

custom actions screenshot

Create your own custom UI

Customization is an important aspect of this library. If need to, you can completely replace the default UI of the player.

YouTubePlayerView has method for that.

View inflateCustomPlayerUi(@LayoutRes int customUiLayoutID)

This method takes in the id of a layout resource, which is a regular XML file containing the definition of a layout. The default UI of the player is removed and replaced with the new UI. The method returns the View object corresponding to the newly inflated layout.

After calling this method, the default PlayerUiController won't be available anymore. Calling YouTubePlayerView.getPlayerUiController() will throw an exception.

You are now responsible for managing your custom UI with your own code. Meaning: you should write your own class to manage the UI. A simple but complete example can be seen here, in the sample app, I recommend taking a few minutes to read it, it should be trivial to understand.

Example (taken from sample app):

View customPlayerUi = youTubePlayerView.inflateCustomPlayerUi(R.layout.custom_player_ui);

youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
  @Override
  public void onReady(@NonNull YouTubePlayer youTubePlayer) {
    YourCustomPlayerUiController customPlayerUiController = new YourCustomPlayerUiController(youTubePlayer, youTubePlayerView, customPlayerUi, ...);
    youTubePlayer.addListener(customPlayerUiController);
    youTubePlayerView.addFullScreenListener(customPlayerUiController);

    // ...
  }
});

A blog post going deeper on this is available at this link.

Example of a custom UI: (this is just a ugly example, but here your design skills are the limit :))

custom ui example

Reusable UI components

The library provides some pre-built UI components, these components are useful to reduce the time needed to build your own UI and controllers.

YouTubePlayerSeekBar

This component is useful to display and control the time of the playback. It shows the current time, the total duration of the video and a seek bar.

YouTubePlayerSeekBar

You can add it to your layout programmatically or in your xml.

<com.pierfrancescosoffritti.androidyoutubeplayer.core.ui.views.YouTubePlayerSeekBar
  android:id="@+id/youtube_player_seekbar"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"

  app:fontSize="12sp"
  app:color="@color/red" />

It is possible to change font size and color by using the fontSize and color attributes.

YouTubePlayerSeekBar implements YouTubePlayerListener. In order for it to work you need to add it as a listener to your YouTubePlayer object.

youTubePlayer.addListener(youTubePlayerSeekBar);

You may wan to listen to events from YouTubePlayerSeekBar, in order to update the current time of your YouTubePlayer when the user moves the touch bar. To do that pass a YouTubePlayerSeekBarListener to YouTubePlayerSeekBar.

youTubePlayerSeekBar.setYoutubePlayerSeekBarListener(new YouTubePlayerSeekBarListener() {
  @Override
  public void seekTo(float time) {
    youTubePlayer.seekTo(time);
  }
});

FadeViewHelper

An helper class that automatically fades out a view when not used. It can be used to automate the fade in and out of a container for the player controls, so that they automatically fade when appropriate.

The FadingFrameLayout is a YouTubePlayerListener therefore it can change it's behavior based on the state of the player. For example: if the video is paused it won't automatically fade out.

You can initialize it by passing to the constructor the view you want to be fading.

FadeViewHelper fadeViewHelper = new FadeViewHelper(controlsContainer);

It is possible to change the animation duration and fade out delay by using the setter methods.

fadeViewHelper.setAnimationDuration(FadeViewHelper.DEFAULT_ANIMATION_DURATION);
fadeViewHelper.setFadeOutDelay(FadeViewHelper.DEFAULT_FADE_OUT_DELAY);

They both take the time in milliseconds.

In order for FadeViewHelper to work properly you need to add it as a listener to your YouTubePlayer object.

youTubePlayer.addListener(fadeViewHelper);

Use the method FadeViewHelper.setDisabled(boolean) to disable the automatic fading.

Use the method FadeViewHelper.toggleVisibility() to toggle the visibility of the target view, with a fade animation.

TimeUtilities

A set of utilities than can be used to format time Strings (like duration and current time of videos).

String TimeUtilities.formatTime(float timeInSeconds)

Takes in the time in seconds and returns a String with the time formatted as "M:SS". (M = minutes, S = seconds).

Web based UI

YouTube added some non-removable buttons to the IFrame Player, as mentioned in this issue. Using the web-based UI is the only way to have access to these non-removable buttons.

To use the web-based UI you can set the attribute app:useWebUi="true" in the YouTubePlayerView.

<com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
  android:id="@+id/youtube_player_view"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"

  app:useWebUi="true" />

Or you can use the appropriate initialization method.

YouTubePlayerView.initializeWithWebUi(YouTubePlayerListener listener, boolean handleNetworkEvents)

When using the web-based UI, calling YouTubePlayerView.getPlayerUiController() throws exception and it is not possible to apply any UI customization.

This is how the player will look when using the web-based ui:

web-based UI

Menu

PlayerUiController has an optional menu. You can use these methods to control the menu's behavior:

PlayerUiController.showMenuButton(boolean show);
PlayerUiController.setMenuButtonClickListener(@NonNull View.OnClickListener customMenuButtonClickListener);

By default the menu icon is not visible.

The default OnClickListener opens the menu when the menu icon is clicked. You can change this behaviour, for example to open a menu with a different UX, like a bottom sheet panel. Obviously if you want a UX different from the one provided by the library, you are responsible for creating your own components.

Menu screenshot:

menu screenshot

YouTubePlayerMenu

You can get a reference of the YouTubePlayerMenu from the PlayerUiController.

YouTubePlayerMenu PlayerUiController.getMenu()

Once you get a YouTubePlayerMenu object you can add and remove items to it, show it and dismiss it.

YouTubePlayerMenu addItem(MenuItem menuItem)
YouTubePlayerMenu removeItem(MenuItem menuItem)
YouTubePlayerMenu removeItem(int itemIndex)

void show(View anchorView)
void dismiss()

Initially the YouTubePlayerMenu doesn't contain any item. You need to add them.

MenuItem

MenuItems are the items of the YouTubePlayerMenu. They have a title, an optional icon and a OnClickListener that is called when the item is clicked.

Network events

YouTubePlayerView automatically handles network events, using an internal BroadcastReceiver. You can choose to enable or disable this feature when initializing the player, or by setting the xml attribute app:handleNetworkEvents="false".

Using the internal BroadcastReceiver is the easiest and recommended way to handle network events. The library is capable of handling cases in which the connection goes off and the playback can't continue, or cases in which the connection goes off while the player is in the process of initialization.

If you want to use your own BroadcastReceiver make sure to cover all the possible scenarios, in order to provide a good user experience.

Chromecast support

If you need to cast YouTube videos to a Chromecast device you can use the chromecast-sender extension library. Read its documentation here.

Useful info

Hardware acceleration

Is important that the Activity containing the YouTubePlayerView is hardware accelerated. This option is enabled by default, you don't have to change anything in your app. Unless you manually disabled hardware acceleration.

If you need to disable hardware acceleration in your application, you can enable it at the Activity level, only for the Activity containing the YouTubePlayerView, as explained here.

Disabling hardware acceleration on the Activity containing YouTubePlayerView may result in some weird behavior. The one I have observed so far shows a black image in the player, while the audio is playing normally.

Play YouTube videos in the background

With this library it's easy to play YouTube videos when the app is not visible. In order to do that you simply have to not call youTubePlayer.pause() when the Activity is being paused or stopped and enable background playback by calling YouTubePlayerView.enableBackgroundPlayback(true).

Adding YouTubePlayerView as an observer to a lifecycle will automatically cause the player to pause the playback when the Activity/Fragment stops.

Therefore if you want your app to keep playing even when the Activity/Fragment is paused/stopped, don't register it as a lifecycle observer and enable background playback for the view. But remember to manually call YouTubePlayerView.release() when the Activity/Fragment is destroyed.

Remember that this behavior is against YouTube terms of service, therefore if you decide to allow background playback you won't be able to publish your app on the Play Store.

Use this functionality only if you plan to build the app for personal use or if you plan to distribute it through different channels.

minSdk

The minSdk of the library is 17. At this point in time it doesn't make much sense for new apps to support older versions of Android.

I'm not sure how WebView will behave on older versions of Android, but technically it should be possible to lower the minSdk. If you absolutely need to support older devices, I suggest you fork the library and lower the minSdk yourself.

How to disable share and watch later buttons

YouTube made some changes to the IFrame player, unfortunately it's not possible to remove those buttons.

If you want to be able to click them, you should use the web-based UI of the player instead of the native UI.

Watch later and share button are in the top right corner, they are visible when the ui is visible:

web-ui screenshot


Chromecast extension library

The chromecast-sender extension library extends the core library with chromecast functionalities. It shares some interfaces with the core library, therefore they can be used together.

The scope of this library is to provide the basic framework and utilities needed to cast YouTube videos to a Chromecast device.

The api of this library is not 100% finalized yet, but is stable. You can use it in your apps.

Quick start - Chromecast

A Google Cast application is made of two components: a Sender and a Receiver.

  • Sender: is responsible for initiating the cast sessions. In our case the sender is an Android app.
  • Receiver: a web app that gets downloaded on the Chromecast when a sender initiates a cast sessions.

Download extra dependencies

To use Google Cast functionalities add the chromecast-sender module to your dependencies:

last-version.

implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:chromecast-sender:last-version'

// this is not needed to use the library, but it provides the quite useful cast button.
implementation 'androidx.mediarouter:mediarouter:last-version'

Sender

In order to use the Google Cast framework an app has to declare a OptionsProvider, as described in the Google Cast documentation.

Add this class to your project:

public final class CastOptionsProvider implements com.google.android.gms.cast.framework.OptionsProvider {
  public com.google.android.gms.cast.framework.CastOptions getCastOptions(Context appContext) {

  // Register you custom receiver on the Google Cast SDK Developer Console to get this ID.
  String receiverId = "";

  return new com.google.android.gms.cast.framework.CastOptions.Builder()
    .setReceiverApplicationId(receiverId)
    .build();
  }

  public List<SessionProvider> getAdditionalSessionProviders(Context context) {
    return null;
  }
}

You can read how to get a receiverId here.

Add the OptionsProvider to your manifest.xmlfile.

(OPTIONS_PROVIDER_CLASS_NAME is meant to be like that, change only the android:value attribute)

<meta-data
  android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
  android:value="yourpackagename.CastOptionsProvider" />

Add a MediaRouterButton to your layout, in your xml file or programmatically.

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/root"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <androidx.mediarouter.app.MediaRouteButton
    android:id="@+id/media_route_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</LinearLayout>

Then in your Activity/Fragment get a reference to the MediaRouteButton and check the status of the GooglePlayServices on the user's phone.

private int googlePlayServicesAvailabilityRequestCode = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  androidx.mediarouter.app.MediaRouteButton mediaRouteButton = findViewById(R.id.media_route_button);
  CastButtonFactory.setUpMediaRouteButton(this, mediaRouteButton);

  // can't use CastContext until I'm sure the user has GooglePlayServices
  PlayServicesUtils.checkGooglePlayServicesAvailability(this, googlePlayServicesAvailabilityRequestCode, this::initChromecast);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  // can't use CastContext until I'm sure the user has GooglePlayServices
  if(requestCode == googlePlayServicesAvailabilityRequestCode)
    PlayServicesUtils.checkGooglePlayServicesAvailability(this, googlePlayServicesAvailabilityRequestCode, this::initChromecast);
}

private void initChromecast() {
  new ChromecastYouTubePlayerContext(
    CastContext.getSharedInstance(this).getSessionManager(),
    new SimpleChromecastConnectionListener()
  );
}

You can easily check the GooglePlayServices status by using PlayServicesUtils.checkGooglePlayServicesAvailability, a utility function provided by the chromecast-sender library.

PlayServicesUtils.checkGooglePlayServicesAvailability does what is described here, in the official doc. It will check the status of GooglePlayServices and will show a dialog to the user if some action is needed in order to fix the problem. It won't display anything if everything is ok (which it is, 99% of the cases), in this case it will simply call the function passed as third parameter. If there are some problems, the result of the operation is delivered through the onActivityResult callback.

Once you're sure the user's GooglePlayServices is all right, you can create the ChromecastYouTubePlayerContext. The access point to the chromecast-sender library.

ChromecastYouTubePlayerContext is the entry point to the chromecast-sender library. Once it is created, it automatically starts listening for Chromecast connection events. The ChromecastConnectionListener passed to the constructor will be used to do just that.

When a user clicks the MediaRouteButton a series of events will be triggered in the framework, use ChromecastConnectionListener's callbacks to be notified of these events.

private class SimpleChromecastConnectionListener implements ChromecastConnectionListener {

  @Override
  public void onChromecastConnecting() {
    Log.d(getClass().getSimpleName(), "onChromecastConnecting");
  }

  @Override
  public void onChromecastConnected(@NonNull ChromecastYouTubePlayerContext chromecastYouTubePlayerContext) {
    Log.d(getClass().getSimpleName(), "onChromecastConnected");
    initializeCastPlayer(chromecastYouTubePlayerContext);
  }

  @Override
  public void onChromecastDisconnected() {
    Log.d(getClass().getSimpleName(), "onChromecastDisconnected");
  }

  private void initializeCastPlayer(ChromecastYouTubePlayerContext chromecastYouTubePlayerContext) {
    chromecastYouTubePlayerContext.initialize(new AbstractYouTubePlayerListener() {
      @Override
      public void onReady(@NonNull YouTubePlayer youTubePlayer) {
        youTubePlayer.loadVideo("S0Q4gqBUs7c", 0f);
      }
    });
  }
}

Only after a Chromecast connection has been established you can initialize the ChromecastConnectionListener.

From now on it will be the same as using a local YouTubePlayer. As you can see in the example, you need to call ChromecastYouTubePlayerContext.initialize, providing a YouTubePlayerListener.

The YouTubePlayerListener will notify you of changes in the playback. You can call loadVideo, cueVideo, pause, play etc.. on the YouTubePlayer object as you're used to, the library will take care of the communication with the Google Cast device.

For how to use the YouTubePlayer object and YouTubePlayerListener, you can refer to the documentation for the core library, YouTubePlayer.

This example can be found in the chromecast-sender sample app, written in Kotlin and in the core sample app, wirtten in Java.

Screenshot of the CastButton added to the YouTubePlayerView:

chromecast button screenshot

Receiver

This library requires a custom receiver, you can find the source code of the chromecast-receiver here.

You don't need to change anything here, it just works. Take this code and upload it (as it is) on your server. (Read the hosting paragraph to learn more about hosting).

Registration

In order to use your receiver you need a receiverId. This is the ID of your receiver app. To get a receiver ID you need to register your receiver on the Google Cast SDK developer console, you can learn how to do it by reading the official documentation. Rember to register a Custom Receiver, this is the type of receiver you need for this library.

Hosting the chromecast-receiver

You will be required to host your receiver somewhere, host it where you prefer. Firebase free hosting may be a good option, for development.


For any question feel free to open an issue on the GitHub repository.

Comments
  • Rejected from Google Play for library use

    Rejected from Google Play for library use

    Unfortunately I don't have many details, but I believe this library caused an app to be rejected from Google Play.

    Not sure which terms of service in particular was broken, just a heads-up.

    I reviewed [app], and had to reject it because it violates our device and network abuse policy. If you submitted an update, the previous version of your app is still live on Google Play.

    Here’s how you can submit your app for another review:

    • Your app shouldn’t access or use a service or API in a manner that violates its terms of service. For example, make sure your app doesn’t download, monetize, or access YouTube videos in a way that violates the YouTube Terms of Service.
    • Read through the Device and Network Abuse policy for more details and examples.
    • Make sure your app is compliant with all other policies listed in the Developer Program Policies. Remember that additional enforcement could occur if there are further policy issues with your apps.
    • Sign in to your Developer Console and submit your app.
    question 
    opened by JakeSteam 34
  • Player is playing automatically

    Player is playing automatically

    Hi, i'm using this awesome library, but i'm facing an issue. To reproduce the problem, play a video in the youtubeplayer. in the middle or the end, don't touch the screen, donc close the activity. Let your phone screen goes off, and after a few seconds or minute, the video start playing, and you can hear the song of the video.

    Sorry for bad english.

    question 
    opened by didiosn 24
  • App crashes on Android 5 - Resources$NotFoundException: String resource ID #0x2040002

    App crashes on Android 5 - Resources$NotFoundException: String resource ID #0x2040002

    The crash is continuously happening for android lollipop micromax and intex devices here is the stacktrace

    com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.WebViewYouTubePlayer. + 25 (WebViewYouTubePlayer.java:25)

      | com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.WebViewYouTubePlayer. + 24 (WebViewYouTubePlayer.java:24)   | com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.LegacyYouTubePlayerView. + 34 (LegacyYouTubePlayerView.java:34)   | com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.LegacyYouTubePlayerView. + 31 (LegacyYouTubePlayerView.java:31)   | com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView. + 30 (YouTubePlayerView.java:30)   | com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView. + 27 (YouTubePlayerView.java:27)

    Please fix it asap

    bug 
    opened by saurabhdtu 23
  • Youtube player not playing on oreo devices

    Youtube player not playing on oreo devices

    I've tested it in Samsung Note 8 & Lenovo K8 note the player is not working it just keeps loading. Even I also tested your Google Play app that also does the same. The issue is occurring on Oreo based devices

    bug 
    opened by shreyan007 22
  • androidx lifecycle observer incompability

    androidx lifecycle observer incompability

    Hey, after plenty of unsuccessful attempts on using the official youtube api together with androidx, I was recommended to use this library- which seems a whole lot more comprehensive and supported. Unfortunately, I'm still stuck with the detail that lifecycle requires observer to be of androidx type.

    build.gradle:

    apply plugin: 'com.android.application'
    apply plugin: 'com.google.android.gms.oss-licenses-plugin'
    
    android {
         compileSdkVersion 28
         defaultConfig {
                  applicationId "com.moomoo.testapp"
                  minSdkVersion 21
                  targetSdkVersion 28
                  versionCode 1
                  versionName "1.0"
         }
    
         buildTypes {
                  release {
                      minifyEnabled false
                      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                  }
          }
     }
     
    dependencies {
         def lifecycle_version = "1.1.1"
         implementation fileTree(include: ['*.jar'], dir: 'libs')
         implementation 'com.google.android.material:material:1.0.0'                  // Material design
         implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'                    // Graphs
         implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:8.0.1'  // Youtube
         implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    }
    
    
    public class SingleTestFragment extends Fragment  {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View rootView = inflater.inflate(R.layout.fragment_single_test, container, false);
    
            YouTubePlayerView youtubePlayerView = rootView.findViewById(R.id.youtube_player_view);
            getLifecycle().addObserver(youtubePlayerView);  <---- issue with androidx and library
            youtubePlayerView.initialize(new YouTubePlayerInitListener() {
                @Override
                public void onInitSuccess(@NonNull final YouTubePlayer initializedYouTubePlayer) {
                    initializedYouTubePlayer.addListener(new AbstractYouTubePlayerListener() {
                        @Override
                        public void onReady() {
                            String videoId = "6JYIGclVQdw";
                            initializedYouTubePlayer.loadVideo(videoId, 0);
                        }
                    });
                }
            }, true);
    
            return rootView;
        }
    }
    

    I wouldnt mind doing the mentioned workaround, of manually releasing the player, if necessary - but I was also unable to figure that one out. Any suggestions?

    enhancement question 
    opened by setzner 21
  • Rejected from Google Play for library use

    Rejected from Google Play for library use

    In 2018 , when i have used this library my app got rejected and after explaing about the app they approved .

    In 2019, I haven't changed anything in apk file . Just updated icon in store listing and my app got rejected saying..

    Issue: Violation of Device and Network Abuse policy

    Every time when i'm updating and submitting for approval , i'm facing challenges about the youtube policy violations. Please let me know how to handle this..

    question 
    opened by rajtechi 19
  • Player is not running in background

    Player is not running in background

    I want to keep the player alive when the app is in background. I'm getting unregisterAudioFocusListener... from logs and the player stops. Are there any ways to keep it alive in background? I tried with a Service but it didn't work.

    Thanks

    bug question 
    opened by gonzalonm 18
  • Error inflating class com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView

    Error inflating class com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView

    I got Error: android.view.InflateException: Binary XML file line #24: Error inflating class com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView p

    I use 'com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.3'

    bug question 
    opened by Hasan-Mahmud 17
  • feat: Make Live mode UI and behaviour in sync with YouTube native app

    feat: Make Live mode UI and behaviour in sync with YouTube native app

    The changes included are :

    1. Introduced Live-VOD (Video on Demand) mode similar which is enabled when user moves the seekbar during live stream.
    2. Live stream indicator tag is made clickable and now has the same functionality as that of native app wherein it'll restore the live state.
    3. Seekbar is always visible now and during Live stream, it's progress position value will be that of the video duration.
    4. Position of Player control UIs are changed to mimic that of the native app.
    opened by rajeefmk 17
  • Video shows blank screen while audio and controls work

    Video shows blank screen while audio and controls work

    Hello, I promise I've read all the threads on issues related to this and I've tried all the suggested remedies but still experiencing the following issues.

    This is the screen that I see, the video view is basically a blank screen but the audio and controls work. Screen Shot 2019-11-11 at 3 53 10 PM

    Here is my resource file, copied straight from the sample app:

    `

        <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
            android:id="@+id/youtube_player_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:autoPlay="true"
            app:videoId="YE7VzlLtp-4"
            app:showYouTubeButton="false"
            app:showSeekBar="false" />
    
    `

    Here is my Activity code:

    override fun onCreate(state: Bundle?) { super.onCreate(state) setContentView(R.layout.activity_ads_video_detail) playerView = findViewById(R.id.youtube_player_view) lifecycle.addObserver(playerView) }

    The environment I'm testing on:

    • Lib version: 10.0.5
    • Kotlin
    • Pixel 2 Emulator, API 23, x86_64
    • Also reproduced on real Pixel 3 Device running API 28
    • Also tried setting hardwareAccelerated=true in the manifest

    I don't think it's a code related issue, but I'm running out of ideas on what to try next... please help! Thank you!

    question 
    opened by jerbotron 16
  • Recyclerview Autoplay onscroll

    Recyclerview Autoplay onscroll

    On scroll I can get the scrolled item position from that I can get the youTubePlayerView but I cannot access the play function as I cannot access the youTubePlayer interface.

    How can I achieve that?

    Thanks in advance

    This is my code

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    int currentPosition = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
                    if (currentPosition == 0|currentPosition > 0){
                        RecyclerView.ViewHolder firstViewHolder = recyclerView.findViewHolderForLayoutPosition(currentPosition);
                        View itemView = Objects.requireNonNull(firstViewHolder).itemView;
                        YouTubePlayerView youTubePlayerView = itemView.findViewById(R.id.youtube_player_view);
                        
                    }
                }
            });
    
    question 
    opened by shreyan007 16
  • React Native: Bridge: Method addObserver must be called on the Main Thread

    React Native: Bridge: Method addObserver must be called on the Main Thread

    Question / Problem

    Summary

    Trying to implement this library into react native. Although followed the SimpleExampleActivity.java

    public class SimpleExampleActivity extends AppCompatActivity {
    
        private YouTubePlayerView youTubePlayerView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_simple_example);
    
            youTubePlayerView = findViewById(R.id.youtube_player_view);
            getLifecycle().addObserver(youTubePlayerView);
        }
    
        @Override
        public void onConfigurationChanged(@NonNull Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
    
            // Checks the orientation of the screen
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                youTubePlayerView.enterFullScreen();
            }
            else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
                youTubePlayerView.exitFullScreen();
            }
        }
    }
    

    The error :

    image

    What i have tried

     runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    getActivity().addObserver(youTubePlayerView);
                }
            });
    

    The problem here is that , this is already an activity , getActivity() will not make sense . Looking for suggestions / help.

    Thanks

    question 
    opened by manoj-paramesh-learngram-ai 2
  • Throwing playback error in a specific android 7 device

    Throwing playback error in a specific android 7 device

    opened by articlp 1
  • issues when trying to hide the menu button

    issues when trying to hide the menu button

    Hi, I want to hide this menu button from the UI. image

    but I get errors when I try to paste the code. should I place it somewhere else ? do I have to initialize anything before pasting the code? I really appreciate any explanation. image

    question 
    opened by xLeDiaa 5
  • YouTube video is flickering, but plays OK after pausing and resuming

    YouTube video is flickering, but plays OK after pausing and resuming

    Bug Report

    Description of the Bug

    I am using this library in a Digital Signage app to play YouTube videos and I received a bug report from one user that a video flickers on their device. I haven't managed to reproduce this bug on any of my devices yet, but I am curious whether anybody has any pointer to what could cause this problem.

    Environment details

    Android Version: 9

    Android System WebView version: 108.0.5359.128

    Tested devices:

    • Xiaomi Mi Box 4

    Youtube Player Library Version: 11.0.1

    Steps to reproduce the bug

    1. Download and install Slideshow app (https://slideshow.digital/how-to-get-it/) on Xiaomi Mi Box 4
    2. Display YouTube video on the screen using the app

    Expected behavior

    The YouTube video plays flicker-free

    Actual behavior

    The YouTube video flickers and there are following messages in the logcat:

    18:43:30.848  4890  5015 E chromium: [ERROR:image_reader_gl_owner.cc(296)] no buffers currently available in the reader queue
    18:43:30.848  4890  5015 E chromium: [ERROR:video_image_reader_image_backing.cc(210)] Failed to get the hardware buffer.
    

    The recording of the behavior is here: https://www.youtube.com/watch?v=-tbXBv9BEQ8

    After manually pausing and resuming the video (using YouTubePlayer.pause() and YouTubePlayer.play()) the video is flicker-free and playback is OK.

    bug 
    opened by milan-fabian 5
  • Please, Explanation in a youtube video :(

    Please, Explanation in a youtube video :(

    Hi, I'm a newbie in programming and especially with AndroidStudio. I'm making an app that requires to import youtubevideos. I read the library and everything.. yet I can't apply what I read, I get a lot of errors and crashes.. so, can anyone please make a youtube video explaining how to customize the UI ?

    opened by xLeDiaa 0
  • add textview to recycler view example

    add textview to recycler view example

    hi! can you please show me an example of adding a textview, or button, or edittext in between any of the vids in the recyclerviewexample? i think you just need to mod recyclerview, the adapter, and add a text or button or edit text xml.

    for example replace one vidid with a string and put it in a textview or something.

    i have a broken example i tried modding yours, but cant upload directories to github from my terminal. i commit but dont see files in my repository. maybe you can just show a quick example until i can figure it out. how do you upload your stuff to github all at once and if the files are over 25mb anyways?

    question 
    opened by buffalopilot 3
Releases(11.1.0)
  • 11.1.0(Aug 6, 2022)

  • 11.0.1(Dec 20, 2021)

  • 11.0.0(Dec 16, 2021)

    • The library has been migrated to MavenCentral, as JCenter is going to disappear soon (#703)
    • Web UI is now the default. This change as been made as web ui is by default compatible with YouTube's terms of service. It's still possible to add custom UIs, but that should be done only if the developer choses to do so. This is a breaking change, the doc has been updated accordingly.
      • The YouTubePlayerView#getUiController method has been removed, as there is no default UI controller now that web ui is the default.
      • Attributes like useWebUi, enableLiveVideoUi, showYouTubeButton etc have been removed, as they don't make sense with web ui as default.
      • The old native UI is now available as DefaultPlayerUiController, you can still use it if you want to.
    • Added support for changing playback speed (#101), thanks to @Serkali-sudo
    • Updates dependencies
    Source code(tar.gz)
    Source code(zip)
    chromecast-sender.v0.25.apk(3.36 MB)
    core.v11.0.0.apk(3.41 MB)
  • 10.0.5(Oct 13, 2019)

  • 10.0.4(Aug 25, 2019)

  • 10.0.1(Feb 18, 2019)

  • 10.0.0(Feb 11, 2019)

    This is a major update, upgrading from an older version will break backward compatibility. The code base has been rewritten in Kotlin and major improvements have been implemented throughout the library.

    Most notably, now YouTubePlayerView:

    • Supports custom attributes, to configure it directly from XML. It is now possible to play a video without writing a single line of Java/Kotlin code. For more advanced use cases everything can also be done programmatically, as before.
    • Can manage its initialization internally! YouTubePlayerInitListener is a thing of the past, it has been removed from the code base. You can now directly add a YouTubePlayerListener to YouTubePlayerView.
    • Can be easily used with the web-based UI instead of the native UI. When using the web-based UI it will be possible to click the "share" and "watch later" buttons that YouTube recently forced to be always visible.

    The documentation has been greatly improved, please use it and feel free to contribute :)

    Follows a detailed description of the changes.

    Breaking changes:

    • YouTubePlayerInitListener has been removed.
    • Every method of YouTubePlayerListener now takes a YouTubePlayer as first argument.
    • Useless parameters have been removed from IFramePlayerOptions, such as autoplay, origin, showInfo and modestBranding. They are deprecated on the IFrame player or not working on mobile devices.
    • The class androidyoutubeplayer.utils.Callable has been removed.
    • The method setYouTubePlayerMenu has been removed from PlayerUIController.
    • The content of the core module is now under a core package.

    New features:

    Improvements:

    • The core module has been rewritten in Kotlin. This doesn't break its compatibility with Java, it just improves the code base.
    • YouTubePlayerView has a new getYouTubePlayerWhenReady method.
    • The utility cueOrLoadVideo has been added, read the documentation to know more.
    • PlayerUIController now has a fluent interface
    • YouTubePlayerMenu now has a fluent interface
    • The dependencies of both the core and chromecast-sender modules have been reorganized in order to import only what's needed.
    • Private resources of the library have been renamed with the "ayt_" prefix.
    • The sample apps have been reorganized and improved with new examples.
    • Both sample apps are now built on top of library-sample-app-template.

    Bugfixes:

    • issue #260
    • issue #295
    Source code(tar.gz)
    Source code(zip)
    sample.v0.18.apk(2.91 MB)
    sample.v10.0.0.apk(2.96 MB)
  • 9.0.1(Dec 10, 2018)

  • 9.0.0(Nov 12, 2018)

    Breaking changes The library is now using Androidx instead of the old support libraries. You may have some problems with the new update if you're using the support library Lifecycle classes. The best way to solve this issue is to migrate your app to Androidx.

    [core] New features IFramePlayerOptions: it is now possible to set some of the IFrame Player parameters from Java/Kotlin, previously this was possible only through Javascript. This opens new customization possibilities, for example it's possible to disable the Android UI of the player and enable the Web UI instead.

    To read more about this feature refer to the doc.

    Thanks to @matthewrkula for implementing this feature.

    [core] Bug Fixes

    • Background playback is working again, read the doc to learn how to enable it. Thanks to @CajetanP for the bug fix.
    • Solved a bug that was hiding custom actions if they were enabled before playing a video.

    [core] Sample app

    • Added Fragment sample app.
    • Added IFramePlayerOptions sample app.
    Source code(tar.gz)
    Source code(zip)
    sample.v0.16.apk(2.90 MB)
    sample.v9.0.0.apk(2.93 MB)
  • 8.0.1(Jun 30, 2018)

    This is the biggest update this library ever had. When I first created the library I didn't intend for it to become a long term project and I lacked the experience to set it up properly. Version 8 fixes most of the bad decisions I made and is supposed to set this project up for success in the long term. Along with these changes a big new feature is now available: Chromecast playback.

    If you are updating from an older version you will have to make some changes in your project, mostly renaming packages and some classes.

    At the end of this post you can find a simple "guide" for updating from version 7 to 8.

    Readme file The readme of the project has been changed heavily, from now on it will contain the documentation of the library.

    Gradle dependency From version 0 to 7 the Gradle dependency of this library has been served through Jitpack. It is now on jCenter instead.

    The YouTube player library is now published under the name core. The Chromecast extension library is published under the name chromecase-sender.

    dependencies {
      implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:8.0.1'
    }
    
    dependencies {
      implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:8.0.1'
      implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:chromecast-sender:0.15'
      
      implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.2.50'
    }
    

    New Features

    • Chromecast playback. A new module has been added to the project: chromecast-sender. This is an extension library that you can use to cast YouTube videos to a Google Cast enabled devices directly from your app. A Chromecast receiver is also provided. Read the documentation for more information.

    Try the sample app here. An example is also available in the core sample app.

    Breaking changes

    • Changed package name of the whole library. It now is com.pierfrancescosoffritti.androidyoutubeplayer. To be consistent with the actual name of the library.
    • Listeners interfaces have been moved in a listeners package.
    • PlayerUIController.setCustomFullScreenButtonListener has been renamed to PlayerUIController.setFullScreenButtonListener
    • YouTubePlayerStateTracker as been renamed to YouTubePlayerTracker.
    • YouTubePlayerTracker.getCurrentState() renamed to YouTubePlayerTracker.getState().
    • Player constants are now enums.

    Minor improvements

    • improved Kotlin compatibility.

    Bug fixes

    • The WebView hosting the player is now detached before is destroyed.

    Migrating from version 7 to 8

    • Change the Gradle dependency from implementation 'com.github.PierfrancescoSoffritti:AndroidYouTubePlayer:6.0.0' to implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:8.0.1'. You can also remove maven { url "https://jitpack.io" } from your project-level build.gradle file.
    • Remove all the imports from your classes, use the IDE to re-import classes from the library from the correct package name.
    • Remember to manually update the package of the Views in your XML files. The IDE may miss them.
    • Apply the changes in the name I have reported under Breaking changes.
    • Convert player constants to enums.
    Source code(tar.gz)
    Source code(zip)
    chromecast-sender-sample-app.v0.15.apk(2.66 MB)
    core-sample-app.v8.0.1.apk(2.68 MB)
  • 7.0.1(Jun 14, 2018)

    Changes:

    • Solved issue #145, when opening a YouTube video by clicking the YouTube button on the player, the video will start playing from where it was stopped.
    • Solved issue #144, it's not possibile to add null YouTubePlayerListeners to YouTubePlayer.
    • Improved compatibility with Kotlin.
    • Improved documentation.
    • Improved sample app.
    Source code(tar.gz)
    Source code(zip)
    sample.v7.0.1.apk(1.27 MB)
  • 7.0.0(May 13, 2018)

    • Breaking changes:

      • YouTubePlayer.seekTo(int time) now takes a float, to improve consistency with the other APIs.
    • Minor changes:

    • When a View is added to the default player UI, using youTubePlayerView.getPlayerUIController().addView(View), it doesn't always need padding. It is now defined in the container.

    • Sample app:

    • Added an example showing how the player state changes and how to track it.

    • Added an example for picture in picture mode.

    • Added nav drawer options to star the library on GitHub and rate on the PlayStore.

    • Links from the main WebView are now opened in the browser.

    Source code(tar.gz)
    Source code(zip)
    sample.v7.0.0.apk(1.27 MB)
  • 6.0.0(Apr 22, 2018)

    • New features:

      • Buffering percentage. It is now possible to know the percentage of the video that has been buffered. You can easily do that adding the method YouTubeListener.onVideoLoadedFraction(float fraction) to your YouTubePlayerListener. The default UI shipped with the library is now showing buffering progress in the player's seek bar. If you don't want to see it, you can hide is using PlayerUIController.showBufferingProgress(boolean show).
    • Minor improvements:

      • Improved documentation in YouTubePlayerListener.
    • Breaking changes:

      • Added method onVideoLoadedFraction(float fraction) to YouTubePlayerListener.
      • Removed onMessage(String message) from YouTubePlayerListener.
      • Removed deprecated methods mute and unMute from YouTubePlayer.
    • Bug fixes:

      • Solved issue #120
    Source code(tar.gz)
    Source code(zip)
    sample.v6.0.0.apk(1.25 MB)
  • 5.0.1(Apr 16, 2018)

    • YouTubePlayer's mute() and unMute() have been deprecated. Use setVolume(int volume) instead.
    • Bugfix: When YouTubePlayerView is registered as a LifecycleObserver, it pauses the video when the lifecycle stops, instead of when it pauses. This improves support for multi-window apps.
    • The sample app has been expanded with a live video example.
    Source code(tar.gz)
    Source code(zip)
    sample.v5.0.1.apk(1.25 MB)
  • 5.0.0(Apr 1, 2018)

    • It is now possible to set a completely custom UI on the player. By calling YouTubePlayerView's method View inflateCustomPlayerUI(@LayoutRes int customPlayerUILayoutID).
      This method takes as argument the ID of a layout resource. This layout will completely replace the default UI of the player.
      After replacing the UI you won't be able to use the default UI controller (getPlayerUIController()), it will be necessary to handle the new UI externally, in your own app. A complete example can be seen here. You can read more here.

    • Removed getCurrentState() method from YouTubePlayer. This method was adding useless noise to the API, therefore it has been removed. A simple utility class has been added to the library in order to provide the same functionality: YouTubePlayerStateTracker. You can read more here.

    • If YouTubePlayerView is added as a lifecycle observer, it will automatically pause when the Activity/Fragment is paused. If you want it to keep playing even when the Activity/Fragment is pause, just don't register it as a lifecycle observer. But remember to manually call release() when the Activity/Fragment is destroyed.

    • Brand new sample app

    • Sample app published on PlayStore

    Source code(tar.gz)
    Source code(zip)
    sample-app-v5.0.0.apk(1.25 MB)
  • 4.1.7(Mar 16, 2018)

  • 4.1.6(Mar 12, 2018)

    • bugfix: player controls UI is now wrapped in a LinearLayout, allowing for more flexibility and proper formatting when hiding/showing control icons
    Source code(tar.gz)
    Source code(zip)
  • 4.1.5(Feb 28, 2018)

  • 4.1.4(Jan 18, 2018)

  • 4.1.3(Jan 17, 2018)

    • YouTubePlayerView is now a lifecycle observer. It's not necessary to call release() destroying the view's context.
    • Added addView and removeView methods to PlayerUIController interface.
    • Bugfix
    Source code(tar.gz)
    Source code(zip)
  • 4.1.2-dev(Jan 17, 2018)

  • 4.1.1-dev(Jan 13, 2018)

  • 4.1.0-dev(Jan 13, 2018)

    • YouTubePlayerView is now a lifecycle observer. It's not necessary to call release() destroying the view's context.
    • Added addView method to PlayerUIController interface.
    Source code(tar.gz)
    Source code(zip)
  • 4.0.0(Jan 11, 2018)

    • Breaking change: PlayerUIController.enableLiveVideoIndicator renamed to PlayerUIController.enableLiveVideoUI
    • Improved UI of the player when playing a live video
    • Improved documentation
    Source code(tar.gz)
    Source code(zip)
  • 3.0.2(Nov 30, 2017)

  • 3.0.1(Nov 22, 2017)

Owner
Pierfrancesco Soffritti
Software engineer @google
Pierfrancesco Soffritti
A highly customizable calendar library for Android, powered by RecyclerView.

CalendarView A highly customizable calendar library for Android, powered by RecyclerView. With this library, your calendar will look however you want

Kizito Nwose 3.4k Jan 3, 2023
A music player UI am designing in Jetpack Compose. The data is being fetched from Deezer's API.

Jetpack-Compose-MusicPlayer-UI ?? - Still under development This is a small project I am doing to interact with and explore Jetpack Compose components

Kagiri Charles 11 Nov 29, 2022
:balloon: A lightweight popup like tooltips, fully customizable with an arrow and animations.

Balloon ?? A lightweight popup like tooltips, fully customizable with arrow and animations. Including in your project Gradle Add below codes to your r

Jaewoong Eum 2.9k Jan 9, 2023
:balloon: A lightweight popup like tooltips, fully customizable with an arrow and animations.

Balloon ?? A lightweight popup like tooltips, fully customizable with arrow and animations. Including in your project Gradle Add below codes to your r

Jaewoong Eum 1.8k Apr 27, 2021
An Easy-to-use Kotlin based Customizable Modules Collection with Material Layouts by BlackBeared.

Fusion By BlackBeared An Easy-to-use Kotlin based Customizable Library with Material Layouts by @blackbeared. Features Custom Floating Action Buttons

Sandip Savaliya 38 Oct 5, 2022
[Android Library] A SharedPreferences helper library to save and fetch the values easily.

Preference Helper A SharedPreferences helper library to save and fetch the values easily. Featured in Use in your project Add this to your module's bu

Naveen T P 13 Apr 4, 2020
Android Ptrace Inject for all ABIs and all APIs. Help you inject Shared Library on Android.

Android Ptrace Inject 中文可以参考我的注释内容进行理解 我写的注释相对来说比较全面了 How to build Make sure you have CMake and Ninja in your PATH Edit CMakeLists.txt. Set ANDROID_ND

SsageParuders 65 Dec 19, 2022
The most complete and powerful data-binding library and persistence infra for Kotlin 1.3, Android & Splitties Views DSL, JavaFX & TornadoFX, JSON, JDBC & SQLite, SharedPreferences.

Lychee (ex. reactive-properties) Lychee is a library to rule all the data. ToC Approach to declaring data Properties Other data-binding libraries Prop

Mike 112 Dec 9, 2022
This library provides common speech features for ASR including MFCCs and filterbank energies for Android and iOS.

Kotlin Speech Features Quick Links ?? Introduction This library is a complete port of python_speech_features in pure Kotlin available for Android and

Merlyn Mind 13 Oct 7, 2022
Oratio Library for Android Studio helps you simplify your Android TTS codes

Oratio Oratio is a library for Android Studio. This library is useful to a number of developers who are currently making apps using android TTS(Text-T

Jacob Lim 1 Oct 28, 2021
A tiny Kotlin multiplatform library that assists in saving and restoring objects to and from disk using kotlinx.coroutines, kotlinx.serialisation and okio

Store A tiny Kotlin multiplatform library that assists in saving and restoring objects to and from disk using kotlinx.coroutines, kotlinx.serialisatio

Isuru Rajapakse 98 Jan 3, 2023
With Viola android face detection library, you can detect faces in a bitmap, crop faces using predefined algorithm and get additional information from the detected faces.

Viola Viola android face detection library detects faces automatically from a bitmap, crop faces using the predefined algorithms, and provides supplem

Darwin Francis 58 Nov 1, 2022
Android Spinner Dialog Library supported on both Java and Kotlin, Use for single or multi selection of choice

SpinnerDialog Android Spinner Dialog Library, Use for single or multi selection of choice Android UI Download To include SpinnerDialog in your project

Hamza Khan 55 Sep 15, 2022
Lightweight data loading and caching library for android

ColdStorage A lightweight data loading and caching library for android Quicklinks Feature requests: Got a new requirement? Request it here and it will

Cryptic Minds 41 Oct 17, 2022
A Kotlin library for reactive and boilerplate-free SharedPreferences in Android

KPreferences A Kotlin library for reactive and boilerplate-free Shared Preferences in Android. With KPreferences you can use Kotlin's marvelous delega

Mohamad Amin Mohamadi 19 Dec 16, 2020
A Bluetooth kotlin multiplatform "Cross-Platform" library for iOS and Android

Blue-Falcon A Bluetooth "Cross Platform" Kotlin Multiplatform library for iOS, Android, MacOS, Raspberry Pi and Javascript. Bluetooth in general has t

Andrew Reed 220 Dec 28, 2022
A Kotlin Android library for content provider queries with reactive streams and coroutines.

Pickpocket An Android library for content provider queries with reactive streams and coroutines. Calendar Contacts SMS MMS Files/Media Call Log Bookma

Chris Basinger 27 Nov 14, 2022
A Kotlin work manager library for Android with progress notifications and Hilt support.

Boot Laces A kotlin work manager library for Android that includes notifications and Hilt support. User Instructions Add the JitPack repository to you

Chris Basinger 35 Oct 8, 2022