How to use MediaRecorder to capture video on Android?
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-permi开发者_运维技巧ssion 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?
First declare the permissions in your Manifest file...
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.Camera"/>
Then in your main app code...
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(); }
To advertise that your application depends on having a camera, put a tag in the manifest file:
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
Record a Video with a Camera App
static final int REQUEST_VIDEO_CAPTURE = 1;
private void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
// View the Video
@Override
protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK)
{
Uri videoUri = intent.getData();
mVideoView.setVideoURI(videoUri);
}
}
精彩评论