Friday, October 5, 2012

Play YouTube video in webView using media player - Android

Using following simple code you can play YouTube video in android media player using WebView. I am trying to play YouTube video from last few days, But today I won.

If  you have any problem in that, So please reply me.


wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginsEnabled(true);
final String mimeType = "text/html";
final String encoding = "UTF-8";
               //Your HTML link for playing video.
               //I used YouTube iframe YouTube Video link
html = getHTML();
wv.setWebChromeClient(new WebChromeClient() {

@Override
public void onShowCustomView(View view, CustomViewCallback callback) {

super.onShowCustomView(view, callback);
Log.e("onShowCustomView", "i m onShowCustomView");
if (view instanceof FrameLayout) {
Log.e("Condin true : view instanceof FrameLayout",
"view instanceof FrameLayout");
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView) {
Log.e("True : frame.getFocusedChild()",
"True : frame.getFocusedChild()");
VideoView video = (VideoView) frame.getFocusedChild();
frame.removeView(video);
setContentView(video);
video.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.stop();
Log.e("mp.stop()", "mp.stop()");
finish();
// setContentView(R.layout.loaddata_qrurl);
}
});
video.setOnErrorListener(new OnErrorListener() {

@Override
public boolean onError(MediaPlayer mp, int what,
int extra) {
Log.e("oNError", "onError");
Toast.makeText(getApplicationContext(),
"Video Error...", 1).show();
return false;
}
});
video.start();
}
}

}

@Override
public void onHideCustomView() {
// TODO Auto-generated method stub
super.onHideCustomView();
Log.e("onHideCustomView", "i m onHideCustomView");
}

@Override
public View getVideoLoadingProgressView() {
// TODO Auto-generated method stub
Log.e("View getVideoLoadingProgressView",
"i m View getVideoLoadingProgressView");
return super.getVideoLoadingProgressView();

}
});
wv.loadDataWithBaseURL("", html, mimeType, encoding, "");



4 comments:

  1. for more reference:
    1. My stackoverflow question
    http://stackoverflow.com/questions/12708890/youtube-video-not-playing-in-webview-android/12751774#12751774

    2. Another good link
    http://pastebin.com/f4cU9T7A

    ReplyDelete
  2. it doesnt work
    if i play it by clicking thumbnail, it turns to blank screen

    ReplyDelete
  3. Hi ,

    Can you Please upload full source code.

    Thanks.

    ReplyDelete
  4. please upload the source code please

    ReplyDelete