Monday, September 2, 2013

how to play youtube video in videoview android ?

You can play youtube video in your application.There is no need to add third party library or other API.


  • First of all create one android project named "VideoViewTube".
  • You need to add VideoView component in your xml file.Open activity_main.xml and add following code:

activity_main.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:minWidth="854dip"
    android:minHeight="480dip"
    >

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fitsSystemWindows="true"
        android:minHeight="480dip"
        android:minWidth="854dip" />

</LinearLayout>


  • If your internet speed is low then It will take some time to play youtube video,Between buffering time and playing time your application UI may freeze.
  • To resolve this issue use Async Task (AsyncTask Tutorial).
  • Open MainActivity.java file and create MyAsyncTask class in below onCreate() method. 
  • MyAsyncTask class extends AsyncTask<Void,Void,Void>,Write following code in MyAsyncTask class.


private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=OtLa7wDpuOU";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
        
            videoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(MainActivity.this);
            videoView.setMediaController(mc);
            videoView.requestFocus();
            videoView.start();          
            mc.show();
        }

    }


  •  Now you get one error in  getUrlVideoRTSP(url).It is because youtube video is RTSP type videos RTSP means Real Time Streaming Protocol.We need to get Video URL from RTSP.
  • Add following two methods below MyAsyncTask class. getUrlVideoRTSP(String urlYoutube); and extractYoutubeId(String url) 


public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            Element el = doc.getDocumentElement();
            NodeList list = el.getElementsByTagName("media:content");///media:content
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

protected static String extractYoutubeId(String url) throws MalformedURLException    {        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }


  • Now just define VideoView and call AsyncTask Class in onCreate() Method.

MainActivity.java


public class MainActivity extends Activity {
VideoView videoView;
String videoUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = (VideoView)findViewById(R.id.videoView);
new YourAsyncTask().execute();
}


  • At last write onPause method in bottom of MainActivity.java class
public void onPause ()
{
super.onPause();
videoView.stopPlayback();
}


The Completed MainActivity.java Class is : Part 2

Get Full Suorce Code: Here



19 comments:

  1. http://www.truiton.com/2013/08/android-youtube-api-tutorial/

    Try this link frds..its works for me!!!

    ReplyDelete
    Replies
    1. i think you use this way for create a backlink for your blog

      Delete
  2. Hi jay.This works for many device.
    You need to also give Internet permission in android menifest for online videos.
    one more thing, the link which is given by you is uses youtube API. which increases your project size.Still you can use it but this is the simple tutorial.

    ReplyDelete
  3. i already given internet permission anyways nice blog pandya.

    ReplyDelete
  4. Hi Parth, I have question about choosing video quality, because when I play video the quality is relay bad and I want to chose better quality.

    ReplyDelete
  5. Nice Tutorial, But not work for me....

    ReplyDelete
  6. nice tutorial parth...it's working fine but is it possible to give more than one link according to the items in gridview or listview...? i am talking about app that is YTmovies...its available on playstore...please give me some hint to clear my idea

    ReplyDelete
  7. @Akshay: Thanks for review. Yes you can use gridview / listview with more than one link and play video on click event.You need to just list video URL with video name.after click on this video you need to only play this video which has URL with same video name. You can also use custom listview /gridviewe for attractive layout.

    ReplyDelete
  8. Those video id have restriction. For them how could we resolved this issue?

    Demo video_id: Q-GLuydiMe4 is not giving the rtsp link.

    ReplyDelete
  9. I try this code it working fine. But few you tube video id not supported to play the videos and not getting rtsp link.

    ReplyDelete
  10. It's Says Can't Play this Video

    ReplyDelete
  11. with vitamio library you can play rtsp directly, but quality not good

    ReplyDelete
  12. Hi Pandya, when i run this code it's say can't play this video.
    Already i have mention internet permission also.

    ReplyDelete
  13. its not working for youtube video

    ReplyDelete
  14. "http://gdata.youtube.com/feeds/api/videos/"

    this link has been deprecated, what should I use in replace with it.

    ReplyDelete