How to Play Video from URL in Android?
In this article, you will see how to play a video from URL on Android. For showing the video in our android application we will use the VideoView widget. The VideoView widget is capable of playing media files, and the formats supported by the VideoView are 3gp and MP4. By using VideoView you can play media files from the local storage and also from the internet. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Now let’s see the step-by-step implementation of the above application shown in the gif.
Step By Step Implementation
Step 1: Create a new project
So the first step is to create a new project, On the Welcome screen of Android Studio, click on Create New Project and If you have a project already opened, Go to File > New > New Project. Then select a Project Template window, select Empty Activity and click Next. Enter your App Name in the Name field and select Java from the Language drop-down menu.
Step 2: Add the Internet Permission
Navigate to app > manifest > AndroidManifest.xml and the internet permission to that file as shown below.
<uses-permission android:name="android.permission.INTERNET"/>
Step 3: Working with the activity_main.xml
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< VideoView
android:id = "@+id/videoView"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_centerInParent = "true" />
</ RelativeLayout >
|
Step 4: Working with the MainActivity.java
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = findViewById(R.id.videoView);
Uri uri = Uri.parse(videoUrl);
videoView.setVideoURI(uri);
MediaController mediaController = new MediaController( this );
mediaController.setAnchorView(videoView);
mediaController.setMediaPlayer(videoView);
videoView.setMediaController(mediaController);
videoView.start();
}
}
|
Output:
Last Updated :
18 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...