How to use MediaRecorder to capture video on Android?

Jonas picture Jonas · Aug 12, 2011 · Viewed 15k times · Source

I would like to create a short video clip using the MediaRecorder, but I don't know how to use it.

In my manifest file I added these permissions before the application-end-tag:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
</application>

And I create a MediaRecorder with this code when the user press a button:

    private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mRecorder.setOutputFile("myvideo.mpeg4");

    try {
        mRecorder.prepare();
    } catch (IOException e) {

    }
    mRecorder.start();
}

But when I run that code I get a "Force close - The application has stopped unexpectedly. Please try again" message. How should I use MediaRecorder and how can I debug my application to see what causes the exception? Do I need to add any other user permissions to my manifest file?

Answer

SoftEye picture SoftEye · Feb 23, 2015

first declare the permission

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.Camera"/>

in Manifestfile then

Camera cam=Camera.open();
cam.unlock();
if(recorder==null)
recorder=new MediaRecorder();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
recorder.setOutputFile(fileName);
recorder.setPreviewDisplay(holder.getSurface());
try{
    recorder.prepare();
    recorder.start();

} catch (IOException e) {
    e.printStackTrace();

}