YouTube Video not playing in WebView – Android

Issue

I am tying to play YouTube video in WebView, WebView showing first look of video with play button, But after click on play button start progress bar and after 2-3 seconds stop progress bar and screen blank with black color.

Image1: Video first look with play button

Image2: After click on play button screen goes blank.

Please! help me why video not starting.

IMAGE:1 This is first look of web view

IMAGE:2 enter image description here

This is my source code to play YouTubeVideo in webview.. Please help me …

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    WebView wv  (WebView) findViewById(R.id.webView1);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setPluginsEnabled(true);
    final String mimeType  "text/html";
    final String encoding  "UTF-8";
    String html  getHTML();
    wv.loadDataWithBaseURL("", html, mimeType, encoding, "");
}

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

Solution

Add these lines before loading HTML content to your WebView.

wv.setWebChromeClient(new WebChromeClient() {
});

From the documentation:

In order to support inline HTML5 video in your application, you need to have hardware acceleration turned on, and set a WebChromeClient. For full screen support, implementations of onShowCustomView(View, WebChromeClient.CustomViewCallback) and onHideCustomView() are required, getVideoLoadingProgressView() is optional.

Answered By – Łukasz Sromek

Leave a Comment