Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play YouTube videos in WebView on Amazon Fire TV?

I want to play a YouTube video in a WebView for Amazon Fire TV.

As of today, there is no official API for playing YouTube videos on Fire OS (link), so I tried to get it working with Android's WebView. In the Android WebView documentation it is written, that the app needs to have hardware acceleration turned on and that the WebView needs to have a WebChromeClient in order to playback YouTube videos.

I tried to get it work but when I start a YouTube video, than I only see the loading spinner in fullscreen mode.

Here is my code:

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

  WebView webview = new WebView(this);
  setContentView(webview);

  webview.getSettings().setBuiltInZoomControls(true);
  webview.getSettings().setJavaScriptEnabled(true);
  webview.setWebChromeClient(new WebChromeClient() {

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
      Log.i("fire-tv", "Show custom view");

      super.onShowCustomView(view, callback);
      if (view instanceof FrameLayout) {
        FrameLayout frame = (FrameLayout) view;
        if (frame.getFocusedChild() instanceof VideoView) {
          VideoView video = (VideoView) frame.getFocusedChild();
          frame.removeView(video);
          setContentView(video);
          video.start();
        }
      }
    }

    @Override
    public void onHideCustomView() {
      Log.i("fire-tv", "Hide custom view.");
    }

  });

  webview.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      return false;
    }

  });

  final String mimeType = "text/html";
  final String encoding = "UTF-8";
  String html = getHTML();

  Log.i("fire-tv", "Loading: " + html);
  webview.loadDataWithBaseURL("", html, mimeType, encoding, "");
}

private String getHTML() {
  String html = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 100%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"
          + "h11u3vtcpaY"
          + "?fs=0\" frameborder=\"0\">\n"
          + "</iframe>\n";

  return html;
}
like image 455
Benny Neugebauer Avatar asked Nov 01 '22 13:11

Benny Neugebauer


1 Answers

Funny thing is, my first answer does answer the question of how to do it with a webview but I found someone else's solution that has a lot of potential using a videoView. Ironically I found it from one of the OPs link:

https://github.com/kslazarev/android-youtube-player

Unlike my solution this plays automatically. Prime video is not affected. There maybe a few other rough edges but this works very well.

like image 140
Ohiovr Avatar answered Nov 14 '22 14:11

Ohiovr