Click here to Skip to main content
Click here to Skip to main content
Go to top

Recording and Playing Video on Android

, , , , 4 Sep 2010
Rate this:
Please Sign up or sign in to vote.
This article attempts to elucidate how to create an application to record and play video. There is also a brief explanation of related APIs
Copyright © 2010 Tata Consultancy Services Ltd. All Rights Reserved

Introduction

Early versions of Android platform did not support video recording and hence the developers were unable to create any video recording applications. With the release of SDK 1.5 (Cupcake) which is based on Linux Kernel 2.6.27, several new features and updates were introduced. This Android version supports video recording and playback.

Android 1.5(Cupcake) and later releases(Donut and Eclair) have APIs for recording video. But, it is difficult to find relevant, lucid and simple articles that explain how to use the Android APIs for recording video. This article attempts to elucidate how to create an application to record and play video. There is also a brief explanation of related APIs.

Video Playback

Android supports playing and recording video under Android Media package. The MediaPlayer Class in this package facilitates video playing.

Creating a media player in other technologies like j2me is more complicated as the customised view needs to be created, the progress slider needs to be handled, etc. However, Android framework makes playing video easy by providing VideoView and Media Controller classes. This additional abstraction handles most of the complications.

VideoView control encapsulates creation and instantiation of MediaPlayer. The VideoView class can load videos from various sources (such as resources or SD card). It takes care of computing measurement from the video so that it can be used in any layout manager, and provides various display options such as scaling and tinting.

MediaController is a view which adds control to the MediaPlayer like play, pause and the progress slider. It synchronizes the controls with the state of the MediaPlayer.

The below section discusses the development of the application for playing video file located on SD card.

Steps To Play Video

Step 1: Create a VideoView Widget

Add VideoView to your layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<VideoView
        android:id="@+id/videoView"
        android:layout_width="200px"
        android:layout_height="200px"
       android:layout_x="10px"
       android:layout_y="10px" />
</LinearLayout>
Step 2: Add it as Content of Activity

Use setContentView method to set content of the activity to the video layout file we created.

@Override
protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          this.setContentView(R.layout.video);
          videoView = (VideoView)this.findViewById(R.id.videoView);
}
Step 3: Set the Path of Video or URI

Use setVideoURI method to set path of the video, the path contains web address of video or location on the SD card.

videoView.setVideoURI(Uri.parse(“Web Address”));

videoView.setVideoURI(Uri.parse(“\sdcard\video.mp4”));

Note: To read the file from web, add the Internet permission to applications' manifest file.

(i.e. Add <uses-permission android:name="android.permission.INTERNET" /> to applications manifest file.)

Step 4: Set the Focus

Call setFocus method of VideoView object to bring VideoView object in focus:

videoView.setFocus();

You can also add MediaController to play, stop, pause and seek through video. Create an object of MediaController class and pass that object to VideoView objects setMediaController method.

MediaController mc = new MediaController(this);
videoView.setMediaController(mc);

Recording Video

This section explains how to record a video on Android. For recording video, MediaRecorder class will be used. To handle the display of camcorder, SurfaceView and SurfaceHolder.Callback interface will be used.

The below section throws light on MediaRecorder, SurfaceView and SurfaceHolder.Callback interface.

  1. MediaRecorder: This class is used to record audio and video. It has different methods to configure the recorder. The methods being used in the Video Recorder are explained below:
    • setVideoSource(): This sets the video source (i.e. Camera or Default) to be used for recording. If this method is not called, the output file will not contain a video track.
    • setOutputFormat(): This sets the format of the output file produced during recording. Call this after setAudioSource()/setVideoSource() but before prepare().
    • setVideoEncoder: This sets the video encoder to be used for recording. If this method is not called, the output file will not contain a video track. Call this after setOutputFormat() and before prepare().
    • setOutputFile(): This sets the path of the output file. Call this after setOutputFormat() but before prepare().
    • setPreviewDisplay(): Sets a Surface to show a preview of recorded media (video). Calls this before prepare() to make sure that the desirable preview display is set.
    • prepare(): Prepares the recorder to begin capturing and encoding data. This method must be called after setting up the desired audio and video sources, encoders, file format, etc., but before start().
    • start(): Begins capturing and encoding data to the file specified with setOutputFile(). Call this after prepare().

    (Note: These methods should be called in the sequence explained above.)

  2. SurfaceView: This is a customized view which provides a drawing surface inside the View hierarchy. It is used for resource intensive tasks where rapid updates or high frame rates are required such as 3D graphics, creating games, or previewing the camera in real time.

    The main advantage of using this view is that it provides an independent thread to update the view, which gives a great user experience.

  3. SurfaceHolder: As the name suggests, this interface holds the SurfaceView object. It allows developers to control the surface size and format, edit the pixels in the surface, and monitor changes to the surface.

Now we can use the above explained APIs to develop a VideoRecording application. We will begin with developing a customized view.

  • Create the RecorderPreview class which extends the SurfaceView and Implements the SurfaceHolder.Callback interface.
    class RecorderPreview extends SurfaceView implements SurfaceHolder.Callback
        {
          //Create objects for MediaRecorder and SurfaceHolder.
          MediaRecorder recorder;
          SurfaceHolder holder;
    
          //Create constructor of Preview Class. In this, get an object of
          //surfaceHolder class by calling getHolder() method. After that add
          //callback to the surfaceHolder. The callback will inform when surface is
          //created/changed/destroyed. Also set surface not to have its own buffers.
    
          public Preview(Contect context,MediaRecorder temprecorder) {
    	 super(context);
              recorder=temprecorder;
    	 holder=getHolder();
    	 holder.addCallback(this);
    	 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
           }
    
          // Implement the methods of SurfaceHolder.Callback interface
    
          // SurfaceCreated : This method gets called when surface is created.
          // In this, initialize all parameters of MediaRecorder object as explained
          // above.
    
          public void surfaceCreated(SurfaceHolder holder){
    	  try{
               	recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
    	   	recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    	   	recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
    	    	recorder.setOutputFile("/sdcard/recordvideooutput.3gpp");
    	    	recorder.setPreviewDisplay(mHolder.getSurface());
    	   	recorder.prepare();
    	    } catch (Exception e) {
    	    	String message = e.getMessage()
          }
    }

    (Note: To allow recording video, add permission into the application's manifest file. i.e. Add <uses-permission android:name="android.permission.RECORD_VIDEO"/>).

    // SurfaceDestroyed : This method gets called immediately before the
    // surface is being destroyed. Stop camera preview because surface will no
    // longer exist.
    
    public void surfaceDestroyed(SurfaceHolder holder)
    {
        if(recorder!=null)
        {
    	recorder.release();
    	recorder = null;
        }
    }
    
    //surfaceChanged : This method is called after the surface is created.
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
    {
    }
    }
  • Implement the onCreate method of video recording application.

    //Create objects of MediaRecorder and Preview class
    private MediaRecorder recorder;
    private Preview preview;
        // In this method, create an object of MediaRecorder class. Create an object of
        // RecorderPreview class(Customized View). Add RecorderPreview class object
        // as content of UI.
    
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        recorder = new MediaRecorder();
        preview = new RecorderPreview(this,recorder);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(preview);
    }
    
    //Create option menu which can be used for starting and stopping video recording.
    // Also implement the onOptionsItemSelected to handle the events for option menu.
    
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, 0, 0, "StartRecording");
        menu.add(0, 1, 0, "StopRecording");
        return super.onCreateOptionsMenu(menu);
    }
    
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case 0:
                recorder.start();
                break;
            case 1:
    	   recorder.stop();
    	   break;
        }
        return super.onOptionsItemSelected(item);
    }

The application is now ready for testing. Video recording is available only on handsets having version of SDK 1.5 or later. It is not possible to check application on emulator, you need to install it on handset.

Conclusion

In this article, we learned how to develop an application for video recording, playback and got an overview of related APIs. A sample application is included with this article. Hopefully, it is useful in developing a video component for your application.

Related Resources

Authors

Sandeep Andre

Sandeep Andre is a Bachelor in Computer Engineering, Pune University. He has worked as a research team member with Mumbai Innovation Labs, Tata Consultancy Services Limited. Currently he is doing his masters in Computer Science at University of North Carolina Charlotte. His research interests are Mobile Computing, Networking and Operating System.
Contact: sandre@uncc.edu.

Suneeta Chawla

Suneeta Chawla is MTech(IT), DAVV University. She is a research team member with Mumbai Innovation Labs, Tata Consultancy Services Limited. Her research interests are Mobile Computing.
Contact: suneeta.chawla@tcs.com.

Pankaj Doke

Pankaj Doke is a Bachelor in Computer Engineering, Mumbai University. He is a research team lead with Mumbai Innovation Labs, Tata Consultancy Services Limited. His research interests are Mobile computing, Computer Security, Pattern Recognition, Machine Learning and Large Scale Systems.
Contact: pankaj.doke@tcs.com.

Sanjay Kimbahune

Sanjay Kimbahune is a Bachelor of Engineering in Electronics, Amravati University. He is a research scientist with Mumbai Innovation Labs, Tata Consultancy Services Limited. His research interests are Mobile Computing and Telecom Systems.
Contact: sanjay.kimbahune@tcs.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Authors

Sandeep Andre

United States United States
No Biography provided

pankajdoke

India India
No Biography provided

No Biography provided

No Biography provided

Comments and Discussions

 
QuestionWhen I run this on my device I get a "Hello World" screen PinmemberCoolSops15-Feb-13 4:53 
QuestionZoom in/out while recording... Pinmemberjunaidas21-Nov-12 20:39 
Questioncode for live streaming video in android Pinmembernagchowdary3-Apr-12 2:02 
AnswerRe: code for live streaming video in android Pinmembernagchowdary16-Apr-12 0:35 
Questioncapturing and playing video with multitasking PinmemberRuby Bautista9-Mar-12 3:26 
QuestionNot working PinmemberTobias Manthey10-Jul-11 2:39 
GeneralNo audio reception Pinmembertauheed12913-Apr-11 2:58 
GeneralRe: No audio reception Pinmemberkash5513-Apr-11 20:22 
GeneralThank YOU! Pinmemberkash556-Apr-11 21:16 
GeneralMy vote of 1 PinmemberVenkatesh Mookkan28-Mar-11 16:30 
Generalvery useful, thanks. PinmemberDavid.Jinyu.Han29-Jan-11 21:39 
GeneralMy vote of 5 Pinmemberchjungen22-Oct-10 7:49 
GeneralMy vote of 3 Pinmember aphazel 死神29-Sep-10 23:32 
GeneralMy vote of 5 Pinmemberloopidio16-Sep-10 1:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 4 Sep 2010
Article Copyright 2010 by Sandeep Andre, pankajdoke, suneetachawla, SanjayKimbahune
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid