Using the Media Recorder Class for Video Capture

If you recall from Chapter 9, video recording was not possible with older versions of the SDK. With 1.5, you can begin to capture video using the media framework. Listing 12-1 demonstrates this. Note that we assume that you have read Chapter 9 and understand how to use the APIs from the media framework. If you have not read Chapter 9, you should do so before continuing with this section. Also realize that Listing 12-1 will not work on an emulator because video recording requires a hardware-encoder module, which is not available with version 1.5 of the SDK. Therefore, you'll have to deploy to a real device to test Listing 12-1.

Listing 12-1. Using the MediaRecorder Class to Capture Video import; import; import android.os.Bundle;

public class MainActivity extends Activity { private MediaRecorder recorder;

^Override public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); setContentView(R.layout.main);

private void recordVideo() throws Exception {

if(recorder!=null) {



recorder = new MediaRecorder();

recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setVideoSize(l76, 144); recorder.setVideoFrameRate(30);

recorder.setVideoEncoder(MediaRecorder.VideoEncoder. MPEG_4_SP);





Listing 12-1 shows an activity class that provides a method to record video content from the device's camera to the SD card. Recall from Chapter 9 that the MediaRecorder requires you to set the recorder properties before calling prepare(). As shown, we set the MediaRecorder's video source to the device's camera, the audio source to the microphone, the output format to 3GPP, and so on. We also set the audio and video encoders and a path to the output file on the SD card before calling the prepare() and start() methods.

Listing 12-1 will capture video content from the camera and output it to the SD card in a file named output.3gpp. As you can see, video recording is fairly easy, as is the audio recording that we showed you in Chapter 9. Note that currently you cannot manipulate the content from the camera before encoding and saving it—you'll have to wait for that, possibly in a later release.

Another notable media-related upgrade is in the android.provider.MediaStore class. Let's explore this class next.

0 0

Post a comment