How to play Youtube video in Android VideoView

In this android programming source code example, we are going to play Youtube video in Android VideoView.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to play Youtube video in Android VideoView.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

MainActivity.java

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoViewActivity9 extends AppCompatActivity {
    private VideoView videoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_view9);
        videoView = (VideoView)findViewById(R.id.videoView);
        //http://m.youtube.com/watch?v=Xprog0HC3aQ&app=m
        videoView.setVideoURI(Uri.parse("rtsp://r5---sn-5hne6n7e.googlevideo.com/Cj0LENy73wIaNAmk3cJBg-iaXhMYDSANFC3zIKlcMOCoAUIASARg1-TDn8fs551cigELTndaSktwMkZqakkM/536C324006419F0313CA2AF625794D8123511074.8916013EBD71B85735FE99BBEC10A978B05AA5E9/yt6/1/video.3gp"));
        videoView.setMediaController(new MediaController(this));
        videoView.requestFocus();
        videoView.start();
    }
}


Note: you need to generate rtsp protocol from your your youtube video by adding &app=m at the back of the video url e.g http://www.youtube.com/watch?v=Xprog0HC3aQ become http://m.youtube.com/watch?v=Xprog0HC3aQ&app=m the right click on the video and copy the generated rtsp protocol.

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment