Android VideoView

Filed Under: Android

In this tutorial, we’ll learn about Android VideoView. We will create an android app in Android Studio and play video from URL, we will also do some customizations to it’s control panel.

Android VideoView

Android VideoView class is used to display Video files in them. Following are the acceptable formats:

  • 3gp
  • MP4 – Only H.263, H.264, H.264 codecs work.

VideoViews can play videos either from resource files, local data or url specified. Following are some of the methods used on VideoView:

  • setVideoURI() – This is used to set the url path. It needs to be parsed as a URI.
  • setVideoPath() – Used for local paths.
  • start()
  • stopPlayback()
  • seekTo(int milliSec)
  • pause()
  • resume()
  • isPlaying()
  • canPause()
  • canSeekForward()
  • canSeekBackward()
  • setOnCompletedListener()
  • addSubtitleSource()
  • setMediaController() : Used to add MediaControls on the Video. Pause/Play, Seek
  • getDuration()
  • setOnPreparedListener() : Gets invoked once the video starts.

Note: VideoView does not retain its full state when going into the background.

In the following section, we’ll be creating an application that runs Videos from urls one after the other.
We’ll see how the MediaController works with the VideoView.

Android VideoView Example

android videoview example

Do not forget to add the Internet Permission in your AndroidManifest.xml file.

Android VideoView Example Code

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.journaldev.videoview.MainActivity">
    
    <TextView
        android:id="@+id/txtPlaceholder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/videoView"
        android:layout_centerHorizontal="true"
        android:layout_margin="16dp"
        android:text="DOUBLE TAP TO VIEW CONTROLS"
        android:textStyle="bold" />


    <VideoView
        android:id="@+id/videoView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

MainActivity.java

The code for the MainActivity.java looks like this:


package com.journaldev.videoview;

import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    VideoView videoView;
    ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"));

    int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoView = findViewById(R.id.videoView);
        final MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(videoView);


        videoView.setMediaController(mediacontroller);
        videoView.setVideoURI(Uri.parse(arrayList.get(index)));
        videoView.requestFocus();

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Toast.makeText(getApplicationContext(), "Video over", Toast.LENGTH_SHORT).show();
                if (index++ == arrayList.size()) {
                    index = 0;
                    mp.release();
                    Toast.makeText(getApplicationContext(), "Video over", Toast.LENGTH_SHORT).show();
                } else {
                    videoView.setVideoURI(Uri.parse(arrayList.get(index)));
                    videoView.start();
                }


            }
        });
        
        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.d("API123", "What " + what + " extra " + extra);
                return false;
            }
        });
    }
}

We’ve added two urls in an ArrayList. We set the anchorView() on the VideoView to keep the MediaControl inside the VideoView.

The output looks something like this:

android videoview app output

Why is the MediaControl outside the VideoView?

Well, the MediaControl doesn’t know the dimensions of the VideoView until the video is started.

For having media control inside the video, we need to set the onPreparedListener on our VideoView and then set the anchor inside it. This way the MediaController is set inside the VideoView.

Our updated MainActivity.java class looks like this now:


package com.journaldev.videoview;

import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    VideoView videoView;
    ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"));
    int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoView = findViewById(R.id.videoView);
        final MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(videoView);


        videoView.setMediaController(mediacontroller);
        videoView.setVideoURI(Uri.parse(arrayList.get(index)));
        videoView.requestFocus();

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                    @Override
                    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                        videoView.setMediaController(mediacontroller);
                        mediacontroller.setAnchorView(videoView);

                    }
                });
            }
        });

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Toast.makeText(getApplicationContext(), "Video over", Toast.LENGTH_SHORT).show();
                if (index++ == arrayList.size()) {
                    index = 0;
                    mp.release();
                    Toast.makeText(getApplicationContext(), "Videos completed", Toast.LENGTH_SHORT).show();
                } else {
                    videoView.setVideoURI(Uri.parse(arrayList.get(index)));
                    videoView.start();
                }


            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.d("API123", "What " + what + " extra " + extra);
                return false;
            }
        });
    }
}

mp.release() is set to release the media player resources. It should be done to prevent memory leaks. Any videoView calls after this line would lead to a CRASH.

Now the output of the above application in action is given below:
android studio videoview tutorial

This brings an end to android video view tutorial. You can download the final Android VideoView project from the link below.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages