Difference between revisions of "Implementing Video Playback on Android 6 using the VideoView and MediaController Classes"

From Techotopia
Jump to: navigation, search
m (Text replacement - "<table border="0" cellspacing="0" width="100%">" to "<table border="0" cellspacing="0">")
m (Text replacement - "<table border="0" cellspacing="0">" to "<table border="0" cellspacing="0" width="100%">")
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
<table border="0" cellspacing="0">
+
<table border="0" cellspacing="0" width="100%">
 
<tr>
 
<tr>
 
<td width="20%">[[An Android 6 Storage Access Framework Example|Previous]]<td align="center">[[Android Studio Development Essentials - Android 6 Edition|Table of Contents]]<td width="20%" align="right">[[Video Recording and Image Capture on Android 6 using Camera Intents|Next]]</td>
 
<td width="20%">[[An Android 6 Storage Access Framework Example|Previous]]<td align="center">[[Android Studio Development Essentials - Android 6 Edition|Table of Contents]]<td width="20%" align="right">[[Video Recording and Image Capture on Android 6 using Camera Intents|Next]]</td>
Line 268: Line 268:
  
  
 +
 +
<htmlet>ezoicbottom</htmlet>
 
<hr>
 
<hr>
<table border="0" cellspacing="0">
+
<table border="0" cellspacing="0" width="100%">
 
<tr>
 
<tr>
 
<td width="20%">[[An Android 6 Storage Access Framework Example|Previous]]<td align="center">[[Android Studio Development Essentials - Android 6 Edition|Table of Contents]]<td width="20%" align="right">[[Video Recording and Image Capture on Android 6 using Camera Intents|Next]]</td>
 
<td width="20%">[[An Android 6 Storage Access Framework Example|Previous]]<td align="center">[[Android Studio Development Essentials - Android 6 Edition|Table of Contents]]<td width="20%" align="right">[[Video Recording and Image Capture on Android 6 using Camera Intents|Next]]</td>

Latest revision as of 20:03, 27 October 2016

PreviousTable of ContentsNext
An Android 6 Storage Access Framework ExampleVideo Recording and Image Capture on Android 6 using Camera Intents


You are reading a sample chapter from the Android Studio 1.x / Android 6 Edition book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book


One of the primary uses for smartphones and tablets is to enable the user to access and consume content. One key form of content widely used, especially in the case of tablet devices, is video.

The Android SDK includes two classes that make the implementation of video playback on Android devices extremely easy to implement when developing applications. This chapter will provide an overview of these two classes, VideoView and MediaController, before working through the creation of a simple video playback application.


Contents


Introducing the Android 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

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(String path) – 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(Uri uri) – 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(MediaPlayer.OnPreparedListener) – Allows a callback method to be called when the video is ready to play.
  • setOnErrorListener(MediaPlayer.OnErrorListener) - Allows a callback method to be called when an error occurs during the video playback.
  • setOnCompletionListener(MediaPlayer.OnCompletionListener) - 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(MediaController) – Designates a MediaController instance allowing playback controls to be displayed to the user.

Introducing the Android MediaController Class

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. This issue can be addressed by attaching an instance of the MediaController class to the VideoView instance. The MediaController will then provide a set of controls allowing the user to manage the playback (such as pausing and seeking backwards/forwards in the video timeline).

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.

You are reading a sample chapter from the Android Studio 1.x / Android 6 Edition book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book

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.

Testing Video Playback

At the time of writing, it is not possible to test video playback when using the Android AVD emulators. To test the video playback functionality of an application it will be necessary to deploy it onto a physical device.

Creating the Video Playback Example

The remainder of this chapter is dedicated to working through an example application intended to use the VideoView and MediaController classes to play a web based MPEG-4 video file.

Create a new project in Android Studio, entering VideoPlayer into the Application name field and ebookfrenzy.com as the Company Domain setting before clicking on the Next button.

On the form factors screen, enable the Phone and Tablet option and set the minimum SDK setting to API 8: Android 2.2 (Froyo). Continue to proceed through the screens, requesting the creation of an empty activity named VideoPlayerActivity with a corresponding layout named activity_video_player.

Designing the VideoPlayer Layout

The user interface for the main activity will simply consist solely of an instance of the VideoView class. Use the Project tool window to locate the app -> res -> layout -> activity_video_player.xml file, double click on it and switch the Designer tool to Design mode. Delete the “Hello world!” TextView, switch to Text mode and remove the padding properties from the layout so that the XML reads as follows:

<?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.ebookfrenzy.videoplayer.VideoPlayerActivity">
</RelativeLayout>

Switch back to Design mode and, from the Containers section of the Palette panel, drag and drop a VideoView instance onto the center point of the layout so that the user interface resembles that of Figure 53-1:


Android studio video view ui 1.4.png

Figure 53-1

You are reading a sample chapter from the Android Studio 1.x / Android 6 Edition book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book

Double click on the VideoView instance in the device screen layout and change the ID of the component to videoView1. Finally, either edit the XML or use the Designer toolbar buttons to change the layout_width and layout_height properties for the VideoView instance to match_parent.

Configuring the VideoView

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 VideoPlayerActivity.java file into the editor and modify the OnCreate() method as outlined in the following listing:

package com.ebookfrenzy.videoplayer;

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

public class VideoPlayerActivity extends AppCompatActivity {

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

        final VideoView videoView =
                (VideoView) findViewById(R.id.videoView1);

        videoView.setVideoPath(
                "http://www.ebookfrenzy.com/android_book/movie.mp4");

        videoView.start();
    }
.
.
.
}

All that this code does is obtain a reference to the VideoView instance in the layout, set the video path on it to point to an MPEG-4 file hosted on a web site and then start the video playing.

Adding Internet Permission

An attempt to run the application at this point would result in the application failing to launch with an error dialog appearing on the Android device that reads “Unable to Play Video. Sorry, this video cannot be played”. This is not because of an error in the code or an incorrect video file format. The issue would be that the application is attempting to access a file over the internet, but has failed to request appropriate permissions to do so. To resolve this, edit the AndroidManifest.xml file for the project and add a line to request internet access:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ebookfrenzy.videoplayer.videoplayer" >

    <uses-permission android:name="android.permission.INTERNET" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
.
.
.


</manifest>

Test the application by running it on a physical Android device. After the application launches there may be a short delay while video content is buffered before the playback begins (Figure 53-2).


Android studio videoplayer running 1.4.png

Figure 53-2


This provides an indication of how easy it can be to integrate video playback into an Android application. Everything so far in this example has been achieved using a VideoView instance and three lines of code.

Adding the MediaController to the Video View

As the VideoPlayer application currently stands, there is no way for the user to control playback. As previously outlined, this can be achieved using the MediaController class. To add a controller to the VideoView, modify the onCreate() method once again:

package com.ebookfrenzy.videoplayer;

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

public class VideoPlayerActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_player);
		
		final VideoView videoView = (VideoView) 
                            findViewById(R.id.videoView1);

		videoView.setVideoPath(
                 "http://www.ebookfrenzy.com/android_book/movie.mp4");
		
		MediaController mediaController = new 
			MediaController(this);
		mediaController.setAnchorView(videoView);
		videoView.setMediaController(mediaController);
		
		videoView.start();		
	}
.
.
.
}

You are reading a sample chapter from the Android Studio 1.x / Android 6 Edition book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book

When the application is launched with these changes implemented, tapping the VideoView canvas will cause the media controls will appear over the video playback. These controls should include a seekbar together with fast forward, rewind and play/pause buttons. After the controls recede from view, they can be restored at any time by tapping on the VideoView canvas once again. With just three more lines of code, our video player application now has media controls as shown in Figure 53-3:


Android studio videoplayer media controller 1.4.png

Figure 53-3

Setting up the onPreparedListener

As a final example of working with video based media, the onCreate() method will now be extended further to demonstrate the mechanism for configuring a listener. In this case, a listener will be implemented that is intended to output the duration of the video as a message in the Android Studio LogCat panel:

package com.ebookfrenzy.videoplayer;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.VideoView;
import android.widget.MediaController;
import android.util.Log;
import android.media.MediaPlayer;

public class VideoPlayerActivity extends AppCompatActivity {

    String TAG = "VideoPlayer";

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

        final VideoView videoView =
                (VideoView) findViewById(R.id.videoView1);

        videoView.setVideoPath(
                "http://www.ebookfrenzy.com/android_book/movie.mp4");

        MediaController mediaController = new
                MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);

        videoView.setOnPreparedListener(new
                MediaPlayer.OnPreparedListener()  {
                     @Override
                     public void onPrepared(MediaPlayer mp) {
                              Log.i(TAG, "Duration = " + 
					videoView.getDuration());
                     }
         });

        videoView.start();

    }
.
.
.
}

Now just before the video playback begins, a message will appear in the Android Studio LogCat panel that reads along the lines of:

11-05 10:27:52.256 12542-12542/com.ebookfrenzy.videoplayer I/VideoPlayer: Duration = 6874

Summary

Tablet based Android devices make excellent platforms for the delivery of content to users, particularly in the form of video media. As outlined in this chapter, the Android SDK provides two classes, namely VideoView and MediaController, which combine to make the integration of video playback into Android applications quick and easy, often involving just a few lines of Java code.


You are reading a sample chapter from the Android Studio 1.x / Android 6 Edition book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book



PreviousTable of ContentsNext
An Android 6 Storage Access Framework ExampleVideo Recording and Image Capture on Android 6 using Camera Intents