1、获得摄像头Feature和写文件的权限
<uses-feature
android:name="android.hardware.camera2"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2、创建一个文件用来保存得到的视频
3、启动Intent进行视频录制<span style="font-size:12px;"> /** * 创建保存录制得到的视频文件 * * @return * @throws IOException */ private File createMediaFile() throws IOException { if (Utils.checkSDCardAvaliable()) { File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_MOVIES), "CameraDemo"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d(TAG, "failed to create directory"); return null; } } // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "VID_" + timeStamp; String suffix = ".mp4"; File mediaFile = new File(mediaStorageDir + File.separator + imageFileName + suffix); return mediaFile; } return null; }</span>
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
try {
fileUri = Uri.fromFile(createMediaFile()); // create a file to save the video
} catch (IOException e) {
e.printStackTrace();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
// start the Video Capture Intent
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
4、在onActivityResult回调里面,通过使用VideoView播放视频
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
//Display the video
vv_play.setVideoURI(fileUri);
vv_play.requestFocus();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
}
然后,你就可以在你设备的外部存储根目录下的/Movies/CameraDemo/目录下面找到你录制的视频,同时在设备的图库里面发现一个新建项"CameraDemo",里面有你录制的视频。在根目录下的/Movies目录的文件是会自动被media scanner进行扫描的,当然我们也可以手动触发系统的media scanner进行扫描,这样就会立即生效。