Introduction to Android VideoView class Android 23.11.2017

Introduction to Android VideoView class

The Android SDK includes two classes (VideoView and MediaController) that make the implementation of video playback on Android devices extremely easy to implement when developing applications. This note will provide an overview of VideoView class.

By far the simplest way to display video within an Android application is to use the VideoView class. This is a visual component which, when added to the layout of an activity, provides a surface onto which a video may be played. Android currently supports the following video formats:

  • H.263
  • H.264 AVC
  • MPEG-4 SP
  • VP8
  • VP9

The VideoView class has a wide range of methods that may be called in order to manage the playback of video. Some of the more commonly used methods are as follows:

  • setVideoPath() specifies the path (as a string) of the video media to be played. This can be either the URL of a remote video file or a video file local to the device.
  • setVideoUri() performs the same task as the setVideoPath() method but takes a Uri object as an argument instead of a string.
  • start() starts video playback.
  • stopPlayback() stops the video playback.
  • pause() pauses video playback.
  • isPlaying() returns a Boolean value indicating whether a video is currently playing.
  • setOnPreparedListener() allows a callback method to be called when the video is ready to play.
  • setOnErrorListener() allows a callback method to be called when an error occurs during the video playback.
  • setOnCompletionListener() allows a callback method to be called when the end of the video is reached.
  • getDuration() returns the duration of the video. Will typically return -1 unless called from within the OnPreparedListener() callback method.
  • getCurrentPosition() returns an integer value indicating the current position of playback.
  • setMediaController() designates a MediaController instance allowing playback controls to be displayed to the user.

If a video is simply played using the VideoView class, the user will not be given any control over the playback, which will run until the end of the video is reached.

The user interface for the main activity will simply consist solely of an instance of the VideoView class.

<?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"
    android:orientation="vertical">

    <VideoView
        android:id="@+id/vvIntro"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

The next step is to configure the VideoView with the path of the video to be played and then start the playback. This will be performed when the main activity has initialized, so load the MainActivity.java file into the editor and modify the OnCreate() method as outlined in the following listing:

public class MainActivity extends AppCompatActivity {
    Activity activity = MainActivity.this;
    VideoView vvIntro;
    int stopPosition = 0;

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

        vvIntro = findViewById(R.id.vvIntro);

        String fileName = "android.resource://"+  getPackageName() + "/" + R.raw.intro;
        vvIntro.setVideoURI(Uri.parse(fileName));

        vvIntro.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                Intent intent = new Intent(activity, RegistrationActivity.class);
                startActivity(intent);
                finish();
            }
        });

        vvIntro.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopPosition = vvIntro.getCurrentPosition();
        vvIntro.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        vvIntro.seekTo(stopPosition);
        vvIntro.start();
    }
}

The MediaController provides a set of controls allowing the user to manage the playback (such as pausing and seeking backwards/forwards in the video time-line).

The position of the controls is designated by anchoring the controller instance to a specific view in the user interface layout. Once attached and anchored, the controls will appear briefly when playback starts and may subsequently be restored at any point by the user tapping on the view to which the instance is anchored.

Some of the key methods of this class are as follows:

  • setAnchorView(View view) – Designates the view to which the controller is to be anchored. This controls the location of the controls on the screen.
  • show() – Displays the controls.
  • show(int timeout) – Controls are displayed for the designated duration (in milliseconds).
  • hide() – Hides the controller from the user.
  • isShowing() – Returns a Boolean value indicating whether the controls are currently visible to the user.

Example

public class MainActivity extends AppCompatActivity {
    private VideoView videoView;
    private MediaController mediaController;

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

        videoView = findViewById(R.id.vv);
        videoView.setVideoPath("http://techslides.com/demos/sample-videos/small.mp4");
        mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);
        videoView.setOnPreparedListener(
                new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.setLooping(true);
                        Log.i("TAG", "Duration = " + videoView.getDuration());
                    }
                });
        videoView.start();
    }
}

Don't forget to add android.permission.INTERNET permission to AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />

WebM format

In an effort to make the web and media more efficient, developers and corporations everywhere are investing effort in creating better file formats and delivery streams. One of the more impressive video formats I've seen is the WebM file format. WebM files are quite small but the quality is still impressive. If you're ready to support and serve WebM, here's how you can convert your traditional file format videos to WebM:

ffmpeg -i trailer.mov -c:v libvpx -crf 10 -b:v 1M -c:a libvorbis trailer.webm