- 浏览: 578207 次
- 性别:
- 来自: 广州
文章分类
- 全部博客 (338)
- 已过时文章(留念用) (39)
- Android学习笔记 (30)
- Android开发指引自译 (100)
- Android NDK文档自译 (23)
- Android设计指引自译 (2)
- xp(ペケピー)&linux(理奈、铃)酱~ (4)
- ui酱&歌词自译~ (9)
- lua酱~ (9)
- 自我反省 (1)
- 羽game计划 (1)
- XSL酱 (2)
- java酱 (3)
- 设计的领悟 (58)
- 涂鸦作品(pixiv) (1)
- ruby酱 (2)
- Objective-C编程语言自译 (2)
- Android开发月报 (6)
- objc酱 (2)
- photoshop (3)
- js酱 (6)
- cpp酱 (8)
- antlr酱 (7)
- Lua 5.1参考手册自译 (11)
- 收藏品 (3)
- 待宵草计划 (4)
- 体验版截图 (1)
最新评论
-
naruto60:
太给力了!!!!我这网打不开Intel官网,多亏楼主贴了连接, ...
使用HAXM加速的Android x86模拟器(和一些问题) -
yangyile2011:
谢谢博主,翻译得很好哦
【翻译】(4)片段 -
ggwang:
牙痛的彼岸:痹!
牙痛的彼岸 -
ggwang:
总结得很简练清晰啊,学习了!
ANTLR学习笔记一:概念理解 -
leisurelife1990:
mk sdd
用git下载Android自带app的源代码
【翻译】(85)照相机
see
http://developer.android.com/guide/topics/media/camera.html
原文见
http://developer.android.com/guide/topics/media/camera.html
-------------------------------
Camera
照相机
-------------------------------
In this document
本文目录
* Considerations 考虑
* The Basics 基础
* Manifest Declarations 清单声明
* Using Existing Camera Apps 使用现存照相机应用
* Image capture intent 图片捕捉意图
* Video capture intent 视频捕捉意图
* Receiving camera intent result 接收照相机意图结果
* Building a Camera App 构建一个照相机应用
* Detecting camera hardware 检测照相机硬件
* Accessing cameras 访问照相机
* Checking camera features 检查照相机特性
* Creating a preview class 创建一个预览类
* Placing preview in a layout 在一个布局中放置预览
* Capturing pictures 捕捉相片
* Capturing videos 捕捉视频
* Releasing the camera 释放照相机
* Saving Media Files 保存媒体文件
* Camera Features 照相机特性
* Checking feature availability 检查特性可用性
* Using camera features 使用照相机特性
* Metering and focus areas 测量和焦点区域
* Face detection 人脸检测
* Time lapse video 慢速视频(注:录影的帧率比正常要慢很多的视频,定时视频)
Key Classes
关键类
Camera
SurfaceView
MediaRecorder
Intent
See also
另见
Media Playback 媒体回放
Data Storage 数据存储
-------------------------------
The Android framework includes support for various cameras and camera features available on devices, allowing you to capture pictures and videos in your applications. This document discusses a quick, simple approach to image and video capture and outlines an advanced approach for creating custom camera experiences for your users.
Android框架包含对各种照相机和在设备上可用的照相机特性的支持,允许你在你的应用程序中捕捉照片和视频。本文讨论图片和视频捕捉的一个快速、简单的方法以及概述为你的用户创建自定义照相机体验的一种高级方法。
-------------------------------
Considerations
考虑
Before enabling your application to use cameras on Android devices, you should consider a few questions about how your app intends to use this hardware feature.
在使能你的应用程序以在Android设备上使用照相机时,你应该考虑关于你的应用打算如何使用这个硬件特性的一些问题。
* Camera Requirement - Is the use of a camera so important to your application that you do not want your application installed on a device that does not have a camera? If so, you should declare the camera requirement in your manifest.
* 照相机要求(注:需要)——照相机的使用对于你的应用程序来说是否太重要以致于你不希望你的应用程序安装在没有一个照相机的设备上?如果那样的话,你应该在你的清单中声明照相机要求。
* Quick Picture or Customized Camera - How will your application use the camera? Are you just interested in snapping a quick picture or video clip, or will your application provide a new way to use cameras? For a getting a quick snap or clip, consider Using Existing Camera Apps. For developing a customized camera feature, check out the Building a Camera App section.
* 快速照片或被定制的照相机——你的应用程序将如何使用照相机?你是否只是感兴趣于拍摄快速照片或视频剪辑,还是你的应用程序将提供一个新的方式来使用照相机?为了获得一个快速拍摄或剪辑,请考虑使用现存照相机应用。为了开发一个被定制的照相机特性,请查看构建一个照相机应用章节。
* Storage - Are the images or videos your application generates intended to be only visible to your application or shared so that other applications such as Gallery or other media and social apps can use them? Do you want the pictures and videos to be available even if your application is uninstalled? Check out the Saving Media Files section to see how to implement these options.
* 存储——你的应用程序生成的照片或视频是否打算只对于你的应用程序可见还是被共享使其它应用程序诸如画廊或其它媒体和社交应用可以使用它们?你是否希望照片和视频是可用的即便你的应用程序被卸载?请查看保存媒体文件章节以了解如何实现这些选择。
-------------------------------
The Basics
基础
The Android framework supports capturing images and video through the Camera API or camera Intent. Here are the relevant classes:
Android框架支持通过Camera的API或照相机Intent来捕捉图片和视频。这里有一些相关的类:
Camera
This class is the primary API for controlling device cameras. This class is used to take pictures or videos when you are building a camera application.
这个类是用于控制设备照相机的主要API。此类被用于照相或录视频,当你正在构建一个照相机应用程序时。
SurfaceView
This class is used to present a live camera preview to the user.
这个类被用于向用户呈现一个现场照相机预览。
MediaRecorder
This class is used to record video from the camera.
这个类被用于从照相机中记录视频。
Intent
An intent action type of MediaStore.ACTION_IMAGE_CAPTURE or MediaStore.ACTION_VIDEO_CAPTURE can be used to capture images or videos without directly using the Camera object.
一个MediaStore.ACTION_IMAGE_CAPTURE或MediaStore.ACTION_VIDEO_CAPTURE的意图动作类型可以被用于捕捉图片或视频而不直接地使用Camera对象。
-------------------------------
Manifest Declarations
清单声明
Before starting development on your application with the Camera API, you should make sure your manifest has the appropriate declarations to allow use of camera hardware and other related features.
在开始使用照相机API在你的应用程序上的开发时,你应该确保你的清单拥有正确的声明以允许照相机硬件和其它相关特性的使用。
* Camera Permission - Your application must request permission to use a device camera.
* 照相机权限——你的应用程序必须请求权限以使用一个设备照相机。
-------------------------------
<uses-permission android:name="android.permission.CAMERA" />
-------------------------------
-------------------------------
Note: If you are using the camera via an intent, your application does not need to request this permission.
注意:如果你正在通过一个意图使用照相机,你的应用程序不需要请求此权限。
-------------------------------
* Camera Features - Your application must also declare use of camera features, for example:
* 照相机特性——你的应用程序还必须声明照相机特性的使用,例如:
-------------------------------
<uses-feature android:name="android.hardware.camera" />
-------------------------------
For a list of camera features, see the manifest Features Reference.
想获得一个照相机特性的列表,请参见清单特性参考手册。
Adding camera features to your manifest causes Google Play to prevent your application from being installed to devices that do not include a camera or do not support the camera features you specify. For more information about using feature-based filtering with Google Play, see Google Play and Feature-Based Filtering.
添加照相机特性到你的清单导致Google Play阻止你的应用程序被安装到不包含一个照相机或不支持你指定的照相机特性的设备。想获得关于使用Google Play的基于特性过滤的更多信息,请参见Google Play和基于特性过滤。
If your application can use a camera or camera feature for proper operation, but does not require it, you should specify this in the manifest by including the android:required attribute, and setting it to false:
如果你的应用程序可以使用一个照相机或照相机特性以获得正确的操作,但并不一定需要它,那么你应该在清单中通过包含android:required属性,并且设置它为false来指定它。
-------------------------------
<uses-feature android:name="android.hardware.camera" android:required="false" />
-------------------------------
* Storage Permission - If your application saves images or videos to the device's external storage (SD Card), you must also specify this in the manifest.
* 存储权限——如果你的应用程序保存图片或视频到设备的外部存储(SD卡),你必须在清单中指定它。
-------------------------------
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-------------------------------
* Audio Recording Permission - For recording audio with video capture, your application must request the audio capture permission.
* 音频记录权限——对于伴随视频捕捉的音频记录,你的应用程序必须请求音频捕捉权限。
-------------------------------
<uses-permission android:name="android.permission.RECORD_AUDIO" />
-------------------------------
* Location Permission - If your application tags images with GPS location information, you must request location permission:
* 位置权限——如果你的应用程序用GPS位置信息标签图片,你必须请求位置权限:
-------------------------------
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
-------------------------------
For more information about getting user location, see Obtaining User Location.
想获得关于获得用户位置的更多信息,请参见获取用户位置。
-------------------------------
Using Existing Camera Apps
使用现存照相机应用
A quick way to enable taking pictures or videos in your application without a lot of extra code is to use an Intent to invoke an existing Android camera application. A camera intent makes a request to capture a picture or video clip through an existing camera app and then returns control back to your application. This section shows you how to capture an image or video using this technique.
在你的应用程序中使能照相或录视频而不使用大量额外代码的一种快捷方法是使用一个Intent来调用一个现存Android照相机应用程序。一个照相机意图作出一个请求以通过一个现存照相机应用捕捉一个相片或视频剪辑,然后把控制权返回给你的应用程序。这个章节向你展示如何使用这项技术捕捉一个图片或视频。
The procedure for invoking a camera intent follows these general steps:
调用一个照相机意图的过程遵循这些通常的步骤:
1. Compose a Camera Intent - Create an Intent that requests an image or video, using one of these intent types:
1. 创作一个照相机意图——创建一个Intent,它请求一个图片或视频,使用这些意图类型中的其中一个:
* MediaStore.ACTION_IMAGE_CAPTURE - Intent action type for requesting an image from an existing camera application.
* MediaStore.ACTION_IMAGE_CAPTURE——意图动作类型,用于从一个现存照相机应用程序中请求一个图片。
* MediaStore.ACTION_VIDEO_CAPTURE - Intent action type for requesting a video from an existing camera application.
* MediaStore.ACTION_VIDEO_CAPTURE——意图动作类型,用于从一个现存照相机应用程序中请求一个视频。
2. Start the Camera Intent - Use the startActivityForResult() method to execute the camera intent. After you start the intent, the Camera application user interface appears on the device screen and the user can take a picture or video.
2. 启动照相机意图——使用startActivityForResult()方法来执行照相机意图。在你启动意图之后,照相机应用程序用户界面出现在设备屏幕上,而用户可以照相或录视频。
3. Receive the Intent Result - Set up an onActivityResult() method in your application to receive the callback and data from the camera intent. When the user finishes taking a picture or video (or cancels the operation), the system calls this method.
3. 接收意图结果——在你的应用程序中配置一个onActivityResult()方法以从照相机意图中接收回调和数据。当用户完成照相或录视频时(或取消操作),系统调用这个方法。
Image capture intent
图片捕捉意图
Capturing images using a camera intent is quick way to enable your application to take pictures with minimal coding. An image capture intent can include the following extra information:
使用一个照相机意图捕捉图片是快捷方法以使能你的应用程序用最小的代码来照相。一个图片捕捉意图可以包含以下额外信息:
* MediaStore.EXTRA_OUTPUT - This setting requires a Uri object specifying a path and file name where you'd like to save the picture. This setting is optional but strongly recommended. If you do not specify this value, the camera application saves the requested picture in the default location with a default name, specified in the returned intent's Intent.getData() field.
* MediaStore.EXTRA_OUTPUT——则个设置需要一个Uri对象指定一个路径和文件名,你喜欢保存相片在那里。这个设置是可选的但是强烈建议的。如果你不指定这个值,那么照相机应用程序保存被请求的相片在默认位置带一个默认的名称,在返回的意图的Intent.getData()域中被指定。
The following example demonstrates how to construct a image capture intent and execute it. The getOutputMediaFileUri() method in this example refers to the sample code shown in Saving Media Files.
以下示例演示如何构建一个图片捕捉意图并且执行它。在这个示例中getOutputMediaFileUri()方法引用了在保存媒体文件中展示的示例代码。
-------------------------------
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create Intent to take a picture and return control to the calling application
// 创建Intent以照相并返回控制给调用方应用程序
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image 创建一个文件以保存图片
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name 设置图片文件名
// start the image capture Intent
// 启动图片捕捉意图
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
-------------------------------
When the startActivityForResult() method is executed, users see a camera application interface. After the user finishes taking a picture (or cancels the operation), the user interface returns to your application, and you must intercept the onActivityResult() method to receive the result of the intent and continue your application execution. For information on how to receive the completed intent, see Receiving camera intent result.
当startActivityForResult()方法被执行时,用户看到一个应用程序界面。在用户完成照相(或取消该操作)之后,用户界面返回到你的应用程序,而你必须拦截onActivityResult()方法以接收意图的结果并且继续你的应用程序的执行。想获得关于如何接收完成意图的信息,请参见接收照相机意图结果。
Video capture intent
视频捕捉意图
Capturing video using a camera intent is a quick way to enable your application to take videos with minimal coding. A video capture intent can include the following extra information:
使用一个照相机意图捕捉视频是一个快捷方法以使能你的应用程序来用最小的代码录视频。一个视频捕捉意图可以包含以下额外信息:
* MediaStore.EXTRA_OUTPUT - This setting requires a Uri specifying a path and file name where you'd like to save the video. This setting is optional but strongly recommended. If you do not specify this value, the Camera application saves the requested video in the default location with a default name, specified in the returned intent's Intent.getData() field.
* MediaStore.EXTRA_OUTPUT——这个设置需要一个Uri指定一个路径和文件名,你喜欢保存视频在那里。这个设置是可选的,但是强烈建议。如果你不指定这个值,那么照相机应用程序保存被请求的视频在默认位置带有一个默认名称,在返回的意图的Intent.getData()域中被指定。
* MediaStore.EXTRA_VIDEO_QUALITY - This value can be 0 for lowest quality and smallest file size or 1 for highest quality and larger file size.
* MediaStore.EXTRA_VIDEO_QUALITY——这个值对于最低质量和最小文件大小可以为0,或者对于最高质量和较大文件大小来说为1。
* MediaStore.EXTRA_DURATION_LIMIT - Set this value to limit the length, in seconds, of the video being captured.
* MediaStore.EXTRA_DURATION_LIMIT——设置这个值以限制正在被捕捉的视频的长度,单位为秒。
* MediaStore.EXTRA_SIZE_LIMIT - Set this value to limit the file size, in bytes, of the video being captured.
* MediaStore.EXTRA_SIZE_LIMIT——设置这个值以限制正在被捕捉的视频的文件大小,单位为字节。
The following example demonstrates how to construct a video capture intent and execute it. The getOutputMediaFileUri() method in this example refers to the sample code shown in Saving Media Files.
以下示例展示如何构造一个视频捕捉意图并执行它。在这个实例中中的getOutputMediaFileUri()方法引用在保存媒体文件中展示的示例代码。
-------------------------------
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
private Uri fileUri;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//create new Intent
//创建新的Intent对象
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // create a file to save the video 创建一个文件以保存视频
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);
}
-------------------------------
When the startActivityForResult() method is executed, users see a modified camera application interface. After the user finishes taking a video (or cancels the operation), the user interface returns to your application, and you must intercept the onActivityResult() method to receive the result of the intent and continue your application execution. For information on how to receive the completed intent, see the next section.
当startActivityForResult()方法被执行时,用户看见一个被修改的照相机应用程序界面。在用户完成录一个视频(或取消该操作)之后,用户界面返回到你的应用程序,而你必须拦截onActivityResult()方法已接收意图的结果和继续你的应用程序的执行。想获得关于如何接收完成意图的信息,请参见下一章节。
Receiving camera intent result
接收照相机意图结果
Once you have constructed and executed an image or video camera intent, your application must be configured to receive the result of the intent. This section shows you how to intercept the callback from a camera intent so your application can do further processing of the captured image or video.
一旦你已经构造和执行一个图片或视频照相机意图,你的应用程序必须被配置以接收意图的结果。这个章节向你展示如何从一个照相机意图中拦截回调,使你的应用程序可以进行对被捕捉图片或视频的进一步处理。
In order to receive the result of an intent, you must override the onActivityResult() in the activity that started the intent. The following example demonstrates how to override onActivityResult() to capture the result of the image camera intent or video camera intent examples shown in the previous sections.
为了接收一个意图的结果,你必须在启动意图的活动中覆盖onActivityResult()。以下示例演示如何覆盖onActivityResult()以捕捉在前面章节中展示的图片照相机意图或视频照相机意图示例的结果。
-------------------------------
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
// 图片被捕捉并保存到在Intent中指定的fileUri
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
// 用户取消图片捕捉
} else {
// Image capture failed, advise user
// 图片捕捉失败,告知(注:建议)用户
}
}
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
// 视频被捕捉并保存到Intent中指定的fileUri
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
// 用户取消视频捕捉
} else {
// Video capture failed, advise user
// 视频捕捉失败,告知(注:建议)用户
}
}
}
-------------------------------
Once your activity receives a successful result, the captured image or video is available in the specified location for your application to access.
一旦你的活动接收到一个成功结果,被捕捉的图片或视频在指定位置是可用的,供你的应用程序访问。
-------------------------------
Building a Camera App
构建一个照相机应用
Some developers may require a camera user interface that is customized to the look of their application or provides special features. Creating a customized camera activity requires more code than using an intent, but it can provide a more compelling experience for your users.
一些开发者可能需要一个照相机用户界面,它被定制为他们的应用程序的外观或提供特殊特性。创建一个被定制的照相机活动需要比使用意图更多的代码,但它可以为你的用户提供一个更引人注目的体验。
The general steps for creating a custom camera interface for your application are as follows:
为你的应用程序创建一个被定制的照相机接口(注:界面)的通常步骤如下:
* Detect and Access Camera - Create code to check for the existence of cameras and request access.
* 检测和访问照相机——创建代码以检查照相机的存在和请求访问权。
* Create a Preview Class - Create a camera preview class that extends SurfaceView and implements the SurfaceHolder interface. This class previews the live images from the camera.
* 创建一个预览类——创建一个照相机预览类,它扩展SurfaceView并且实现SurfaceHolder接口。这个类预览来自照相机的现场图片。
* Build a Preview Layout - Once you have the camera preview class, create a view layout that incorporates the preview and the user interface controls you want.
* 构建一个预览布局——一旦你拥有照相机预览类,请创建一个视图布局,它包含你想要的预览和用户界面控件。
* Setup Listeners for Capture - Connect listeners for your interface controls to start image or video capture in response to user actions, such as pressing a button.
* 为捕捉配置监听器——连接你的界面控件的监听器以启动图片或视频捕捉来响应用户动作,诸如按下一个按钮。
* Capture and Save Files - Setup the code for capturing pictures or videos and saving the output.
* 捕捉和保存文件——配置用于捕捉照片或视频和保存输出的代码。
* Release the Camera - After using the camera, your application must properly release it for use by other applications.
* 释放照相机——在使用照相机后你的应用程序必须正确地释放它,以便让其它应用程序使用它。
Camera hardware is a shared resource that must be carefully managed so your application does not collide with other applications that may also want to use it. The following sections discusses how to detect camera hardware, how to request access to a camera, how to capture pictures or video and how to release the camera when your application is done using it.
照相机硬件是一个共享资源,它必须被小心地管理,使你的应用程序不与也可能希望使用它的其它应用程序冲突。以下章节讨论如何检测照相机硬件,如何请求访问一个照相机,如何捕捉相片或视频,以及当你的应用程序完成使用它时如何释放照相机。
-------------------------------
Caution: Remember to release the Camera object by calling the Camera.release() when your application is done using it! If your application does not properly release the camera, all subsequent attempts to access the camera, including those by your own application, will fail and may cause your or other applications to be shut down.
警告:记得当你的应用程序用完它时,通过调用Camera.release()释放Camera对象!如果你的应用程序不正确地释放照相机,那么所有随后访问照相机的尝试,包括那些你自己的应用程序作出的尝试,将失败并且可能导致你的或其它应用程序被关闭。
-------------------------------
Detecting camera hardware
检测照相机硬件
If your application does not specifically require a camera using a manifest declaration, you should check to see if a camera is available at runtime. To perform this check, use the PackageManager.hasSystemFeature() method, as shown in the example code below:
如果你的应用程序不特别地使用一个清单声明来需要一个照相机,你应该在运行时检查以了解照相机是否可用。为了执行这种检查,请使用PackageManager.hasSystemFeature()方法,正如下面的示例代码中所示:
-------------------------------
/** Check if this device has a camera */
/** 检查这台设备是否拥有照相机 */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
// 这台设备拥有照相机
return true;
} else {
// no camera on this device
// 这台设备上没有照相机
return false;
}
}
-------------------------------
Android devices can have multiple cameras, for example a back-facing camera for photography and a front-facing camera for video calls. Android 2.3 (API Level 9) and later allows you to check the number of cameras available on a device using the Camera.getNumberOfCameras() method.
Android设备可以拥有多个照相机,例如一个后置照相机用于照相和一个前置照相机用于视频通话。Android 2.3(API级别9)和更新的版本允许你使用Camera.getNumberOfCameras()方法检查一台设备上可用的照相机数量。
Accessing cameras
访问照相机
If you have determined that the device on which your application is running has a camera, you must request to access it by getting an instance of Camera (unless you are using an intent to access the camera).
如果你已经确定在你的应用程序运行在的设备上拥有一个照相机,你必须通过获得一个Camera实例来请求访问它(除非你正在使用一个意图来访问照相机)。
To access the primary camera, use the Camera.open() method and be sure to catch any exceptions, as shown in the code below:
为了访问主照相机,请使用Camera.open()方法并确保捕捉任意异常,正如下面代码中所示:
-------------------------------
/** A safe way to get an instance of the Camera object. */
/** 一种安全的方式以获得一个Camera对象的实例。 */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance 尝试获得一个Camera实例
}
catch (Exception e){
// Camera is not available (in use or does not exist)
// 照相机不可用(正在使用或不存在)
}
return c; // returns null if camera is unavailable 返回null如果照相机不可用
}
-------------------------------
-------------------------------
Caution: Always check for exceptions when using Camera.open(). Failing to check for exceptions if the camera is in use or does not exist will cause your application to be shut down by the system.
警告:当使用Camera.open()时总是检查异常。检查异常失败,如果照相机正在使用或不存在,将导致你的应用程序被系统关闭。
-------------------------------
On devices running Android 2.3 (API Level 9) or higher, you can access specific cameras using Camera.open(int). The example code above will access the first, back-facing camera on a device with more than one camera.
在运行Android 2.3(API级别9)或更高的设备上,你可以使用Camera.open(int)访问指定照相机。上面的示例代码将访问带多于一个照相机的设备上第一个背向照相机(注:后置摄像头,一般叫Rear camera,是指照相手机背后的摄像头,是相对Front Facing Camera而言的。可能比正常的数码相机要省电些)。
Checking camera features
检查照相机特性
Once you obtain access to a camera, you can get further information about its capabilities using the Camera.getParameters() method and checking the returned Camera.Parameters object for supported capabilities. When using API Level 9 or higher, use the Camera.getCameraInfo() to determine if a camera is on the front or back of the device, and the orientation of the image.
一旦你取得对一个照相机的访问权,你可以使用Camera.getParameters()方法获得关于它的能力的进一步信息并且针对被支持的能力检查返回的Camera.Parameters对象。当使用API级别9或更高时,请使用Camera.getCameraInfo()以确定一个找星际是在设备的前方还是在后方,以及图片的方向。
Creating a preview class
创建一个预览类
For users to effectively take pictures or video, they must be able to see what the device camera sees. A camera preview class is a SurfaceView that can display the live image data coming from a camera, so users can frame and capture a picture or video.
为了让用户有效地照相或录视频,他们必须有能力了解设备照相机看到什么。一个照相机预览类是一个SurfaceView,它可以显示来自一个照相机的现场图片数据,那样用户可以框定(注:待考)和捕捉一个相片或视频。
The following example code demonstrates how to create a basic camera preview class that can be included in a View layout. This class implements SurfaceHolder.Callback in order to capture the callback events for creating and destroying the view, which are needed for assigning the camera preview input.
以下示例代码演示如何创建一个基本照相机预览类,它可以被包含在一个View布局中。这个类实现SurfaceHolder.Callback以便捕捉创建和销毁视图的回调事件,需要用它们来赋予(注:指定)照相机预览的输入。
-------------------------------
/** A basic Camera preview class */
/** 一个基本的Camera预览类 */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
// 安装一个SurfaceHolder.Callback那样当底层表面被创建和销毁时我们被通知。
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
// 被废弃的设置,但在3.0之前的Android版本上是必需的
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
// Surface已经被创建,现在告诉照相机在哪里绘画预览。
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
// 空。小心在你的活动中释放Camera预览
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
// 如果你的预览可以改变或旋转,请小心这里的那些事件。
// 确保在改变大小或重新格式化它之前停止预览。
if (mHolder.getSurface() == null){
// preview surface does not exist
// 预览表面不存在
return;
}
// stop preview before making changes
// 在作出改变之前停止预览
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
// 忽略:尝试停止一个不存在的预览
}
// set preview size and make any resize, rotate or
// reformatting changes here
// 在这里设置预览大小并作出任意的改变大小,旋转或
// 重新格式化的改变。
// start preview with new settings
// 用新的设置开始预览
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
-------------------------------
If you want to set a specific size for your camera preview, set this in the surfaceChanged() method as noted in the comments above. When setting preview size, you must use values from getSupportedPreviewSizes(). Do not set arbitrary values in the setPreviewSize() method.
如果你希望为你的照相机预览设置一个特定的大小,请在surfaceChanged()方法中设置它,正如上面的注释中所注明的。当设置预览大小时,你必须使用来自getSupportedPreviewSizes()的值。不要在setPreviewSize()方法里设置任意值。
Placing preview in a layout
在布局中放置预览
A camera preview class, such as the example shown in the previous section, must be placed in the layout of an activity along with other user interface controls for taking a picture or video. This section shows you how to build a basic layout and activity for the preview.
一个照相机预览类,诸如在前一章节中所示的例子,必须被放置在一个活动的布局内伴随其他用户界面控件,用于照相或录视频。这个章节向你展示如何为该预览构建一个基本布局和活动。
The following layout code provides a very basic view that can be used to display a camera preview. In this example, the FrameLayout element is meant to be the container for the camera preview class. This layout type is used so that additional picture information or controls can be overlayed on the live camera preview images.
以下布局代码提供一个非常基本的视图,它可以被用于显示一个照相机预览。在这个示例中,FrameLayout元素打算做照相机预览类的容器。这个布局类型被使用,使额外的相片信息或控件(注:控制)可以在现场照相机预览图片上被覆盖。
-------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
<Button
android:id="@+id/button_capture"
android:text="Capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
-------------------------------
On most devices, the default orientation of the camera preview is landscape. This example layout specifies a horizontal (landscape) layout and the code below fixes the orientation of the application to landscape. For simplicity in rendering a camera preview, you should change your application's preview activity orientation to landscape by adding the following to your manifest.
在大多数设备上,照相机预览的默认方向是宽屏方向。这个示例布局指定一个水平(宽屏)的布局,而下面的代码固定(注:修复)应用程序的方向为水平方向。为了简化渲染一个照相机预览,你应该改变你的应用程序的预览活动方向为宽屏方向,通过添加以下内容到你的清单中。
-------------------------------
<activity android:name=".CameraActivity"
android:label="@string/app_name"
android:screenOrientation="landscape">
<!-- configure this activity to use landscape orientation -->
<!-- 配置这个活动以使用宽屏方向 -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
-------------------------------
-------------------------------
Note: A camera preview does not have to be in landscape mode. Starting in Android 2.2 (API Level 8), you can use the setDisplayOrientation() method to set the rotation of the preview image. In order to change preview orientation as the user re-orients the phone, within the surfaceChanged() method of your preview class, first stop the preview with Camera.stopPreview() change the orientation and then start the preview again with Camera.startPreview().
注意:一个照相机预览不一定处于宽屏模式。在Android 2.2开始(API级别8),你可以使用setDisplayOrientation()方法以设置预览图片的旋转。为了在用户改变电话方向时改变预览方向,在你的预览类的surfaceChanged()方法内,首先用Camera.stopPreview()停止预览,改变方向,然后再次用Camera.startPreview()启动预览。
-------------------------------
In the activity for your camera view, add your preview class to the FrameLayout element shown in the example above. Your camera activity must also ensure that it releases the camera when it is paused or shut down. The following example shows how to modify a camera activity to attach the preview class shown in Creating a preview class.
在你的照相机视图的活动中,添加你的预览类到上面示例中展示的FrameLayout元素。你的照相机活动还必须确保它释放照相机,当它被暂停或被关闭。以下示例展示如何修改照相机活动以依附在创建一个预览类中展示的预览类。
-------------------------------
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create an instance of Camera
// 创建一个Camera实例
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
// 创建我们的预览视图并设置它作为我们的活动的内容。
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);
preview.addView(mPreview);
}
}
-------------------------------
-------------------------------
Note: The getCameraInstance() method in the example above refers to the example method shown in Accessing cameras.
注意:在上面的示例中getCameraInstance()方法引用在访问照相机中展示的示例方法。
-------------------------------
Capturing pictures
捕捉相片
Once you have built a preview class and a view layout in which to display it, you are ready to start capturing images with your application. In your application code, you must set up listeners for your user interface controls to respond to a user action by taking a picture.
一旦你已经构建一个预览类和一个在其中显示它的视图布局,你就准备好开始用你的应用程序捕捉图片。在你的应用程序代码中,你必须为你的用户界面控件配置监听器以响应由照相引发的用户动作(注:待考)。
In order to retrieve a picture, use the Camera.takePicture() method. This method takes three parameters which receive data from the camera. In order to receive data in a JPEG format, you must implement an Camera.PictureCallback interface to receive the image data and write it to a file. The following code shows a basic implementation of the Camera.PictureCallback interface to save an image received from the camera.
为了取出一个相片,请使用Camera.takePicture()方法。这个方法传入三个参数,它们从照相机中接收数据。为了接收JPEG格式的数据,你必须实现一个Camera.PictureCallback接口以接收图片数据和写入它到一个文件。以下代码展示Camera.PictureCallback接口的一个基本实现以保存一个接收自照相机的一个图片。
-------------------------------
private PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: " +
e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
-------------------------------
Trigger capturing an image by calling the Camera.takePicture() method. The following example code shows how to call this method from a button View.OnClickListener.
通过调用Camera.takePicture()方法触发捕捉一个图片。以下示例代码展示如何从一个按钮View.OnClickListener中调用这个方法。
-------------------------------
// Add a listener to the Capture button
// 添加一个监听器到捕捉按钮
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// get an image from the camera
// 从照相机中获得一个图片
mCamera.takePicture(null, null, mPicture);
}
}
);
-------------------------------
-------------------------------
Note: The mPicture member in the following example refers to the example code above.
注意:在以下示例中mPicture成员引用上面的示例代码。
-------------------------------
-------------------------------
Caution: Remember to release the Camera object by calling the Camera.release() when your application is done using it! For information about how to release the camera, see Releasing the camera.
警告:记得通过调用Camera.release()释放Camera对象,当你的引用程序已经完成使用它时!想获得关于如何释放照相机的信息,请参见释放照相机。
-------------------------------
Capturing videos
捕捉视频
Video capture using the Android framework requires careful management of the Camera object and coordination with the MediaRecorder class. When recording video with Camera, you must manage the Camera.lock() and Camera.unlock() calls to allow MediaRecorder access to the camera hardware, in addition to the Camera.open() and Camera.release() calls.
使用Android框架的视频捕捉需要Camera对象的小心管理以及与MediaRecorder类协调。当使用照相机记录视频时,你必须管理Camera.lock()和Camera.unlock()调用以允许MediaRecorder访问照相机硬件,除Camera.open()和Camera.release()调用以外。
-------------------------------
Note: Starting with Android 4.0 (API level 14), the Camera.lock() and Camera.unlock() calls are managed for you automatically.
注意:从Android 4.0(API级别14)开始,自动地为你管理Camera.lock()和Camera.unlock()调用。
-------------------------------
Unlike taking pictures with a device camera, capturing video requires a very particular call order. You must follow a specific order of execution to successfully prepare for and capture video with your application, as detailed below.
不像用一个设备照相机照相那样,捕捉视频需要一个非常特殊的调用顺序。你必须遵循一个特定执行次序以成功地准备和捕捉你的应用程序的视频,正如下面的详细说明那样。
1. Open Camera - Use the Camera.open() to get an instance of the camera object.
1. 打开照相机——使用Camera.open()以获得一个照相机对象的实例。
2. Connect Preview - Prepare a live camera image preview by connecting a SurfaceView to the camera using Camera.setPreviewDisplay().
2. 连接预览——准备一个现场照相机图片预览,通过使用Camera.setPreviewDisplay()连接一个SurfaceView到照相机。
3. Start Preview - Call Camera.startPreview() to begin displaying the live camera images.
3. 开始预览——调用Camera.startPreview()以开始显示现场照相机图片。
4. Start Recording Video - The following steps must be completed in order to successfully record video:
4. 开始记录视频——为了成功地记录视频,以下步骤必须被完成:
a. Unlock the Camera - Unlock the camera for use by MediaRecorder by calling Camera.unlock().
a. 解锁照相机——为了通过MediaRecorder来使用,通过调用Camera.unlock()解锁照相机。(注:待考)
b. Configure MediaRecorder - Call in the following MediaRecorder methods in this order. For more information, see the MediaRecorder reference documentation.
b. 配置MediaRecorder——在以下MediaRecorder方法中以这个次序来调用。想获得更多信息,请参见MediaRecorder参考文档。
1. setCamera() - Set the camera to be used for video capture, use your application's current instance of Camera.
1. setCamera()——设置照相机以被用于视频捕捉,使用你的应用程序的当前Camera实例。
2. setAudioSource() - Set the audio source, use MediaRecorder.AudioSource.CAMCORDER.
2. setAudioSource()——设置音频源,使用MediaRecorder.AudioSource.CAMCORDER。
3. setVideoSource() - Set the video source, use MediaRecorder.VideoSource.CAMERA.
3. setVideoSource()——设置视频源,使用MediaRecorder.VideoSource.CAMERA。
4. Set the video output format and encoding. For Android 2.2 (API Level 8) and higher, use the MediaRecorder.setProfile method, and get a profile instance using CamcorderProfile.get(). For versions of Android prior to 2.2, you must set the video output format and encoding parameters:
4. 设置视频输出格式和编码。对于Android 2.2(API级别8)和更高,请使用MediaRecorder.setProfile方法,并且使用CamcorderProfile.get()取得一个简介(注:剖析)实例。对于2.2之前的Android版本,你必须设置视频输出格式和编码参数:
i. setOutputFormat() - Set the output format, specify the default setting or MediaRecorder.OutputFormat.MPEG_4.
i. setOutputFormat()——设置输出格式,指定默认设置或MediaRecorder.OutputFormat.MPEG_4
ii. setAudioEncoder() - Set the sound encoding type, specify the default setting or MediaRecorder.AudioEncoder.AMR_NB.
ii. setAudioEncoder()——设置声音编码类型,指定默认设置或MediaRecorder.AudioEncoder.AMR_NB。
iii. setVideoEncoder() - Set the video encoding type, specify the default setting or MediaRecorder.VideoEncoder.MPEG_4_SP.
iii. setVideoEncoder()——设置视频编码类型,指定默认默认设置或MediaRecorder.VideoEncoder.MPEG_4_SP。
5. setOutputFile() - Set the output file, use getOutputMediaFile(MEDIA_TYPE_VIDEO).toString() from the example method in the Saving Media Files section.
5. setOutputFile()——设置输出文件,使用来自保存媒体文件章节中的示例方法的getOutputMediaFile(MEDIA_TYPE_VIDEO).toString()。
6. setPreviewDisplay() - Specify the SurfaceView preview layout element for your application. Use the same object you specified for Connect Preview.
6. setPreviewDisplay()——指定你的应用程序的SurfaceView预览布局元素。使用你为连接预览所指定的相同对象。
-------------------------------
Caution: You must call these MediaRecorder configuration methods in this order, otherwise your application will encounter errors and the recording will fail.
警告:你必须按这个次序调用这些MediaRecorder配置方法,否则你的应用程序将遇到错误而且记录将失败。
-------------------------------
c. Prepare MediaRecorder - Prepare the MediaRecorder with provided configuration settings by calling MediaRecorder.prepare().
c. 准备MediaRecorder——通过调用MediaRecorder.prepare()用提供的配置设置准备MediaRecorder。
d. Start MediaRecorder - Start recording video by calling MediaRecorder.start().
d. 启动MediaRecorder——通过调用MediaRecorder.start()开始记录视频。
5. Stop Recording Video - Call the following methods in order, to successfully complete a video recording:
5. 停止记录视频——依次调用以下方法,以成功地完成一个视频记录:
a. Stop MediaRecorder - Stop recording video by calling MediaRecorder.stop().
a. 停止MediaRecorder——通过调用MediaRecorder.stop()停止记录视频。
b. Reset MediaRecorder - Optionally, remove the configuration settings from the recorder by calling MediaRecorder.reset().
b. 重置MediaRecorder——可选地,通过调用MediaRecorder.reset()从记录器中移除配置设置。
c. Release MediaRecorder - Release the MediaRecorder by calling MediaRecorder.release().
c. 释放MediaRecorder——通过调用MediaRecorder.release()释放MediaRecorder。
d. Lock the Camera - Lock the camera so that future MediaRecorder sessions can use it by calling Camera.lock(). Starting with Android 4.0 (API level 14), this call is not required unless the MediaRecorder.prepare() call fails.
d. 锁定照相机——锁定照相机,使得未来的MediaRecorder会话可以通过调用Camera.lock()来使用它。从Android 4.0(API级别14)开始,这个调用不是必需的,除非MediaRecorder.prepare()调用失败。
6. Stop the Preview - When your activity has finished using the camera, stop the preview using Camera.stopPreview().
6. 停止预览——当你的活动已经完成使用照相机,请使用Camera.stopPreview()停止预览。
7. Release Camera - Release the camera so that other applications can use it by calling Camera.release().
7. 释放照相机——通过调用Camera.release()释放照相机以使得其它应用程序可以使用它。
-------------------------------
Note: It is possible to use MediaRecorder without creating a camera preview first and skip the first few steps of this process. However, since users typically prefer to see a preview before starting a recording, that process is not discussed here.
注意:可以使用MediaRecorder而不首先创建一个照相机预览和跳过这个处理开头的几个步骤。然而,因为用户通常倾向于在开始一个记录前看到一个预览,所以那种处理不在这里讨论。
-------------------------------
-------------------------------
Tip: If your application is typically used for recording video, set setRecordingHint(boolean) to true prior to starting your preview. This setting can help reduce the time it takes to start recording.
提示:如果你的应用程序被惯常地用于记录视频,请在开始你的预览之前设置setRecordingHint(boolean)为true。这个设置可以有助于缩短它用于开始记录的时间。
-------------------------------
Configuring MediaRecorder
配置MediaRecorder
When using the MediaRecorder class to record video, you must perform configuration steps in a specific order and then call the MediaRecorder.prepare() method to check and implement the configuration. The following example code demonstrates how to properly configure and prepare the MediaRecorder class for video recording.
当使用MediaRecorder类来记录视频时,你必须以一个特定次序执行配置步骤,然后调用MediaRecorder.prepare()方法以检查和实现配置。以下示例代码演示如何为了视频记录而正确地配置和准备MediaRecorder类。
-------------------------------
private boolean prepareVideoRecorder(){
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
// Step 1: Unlock and set camera to MediaRecorder
// 步骤1:解锁并设置照相机到MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
// 步骤2:设置源
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
// 步骤3:设置一个CamcorderProfile(需要API级别8或更高)
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// Step 4: Set output file
// 步骤4:设置输出文件
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
// Step 5: Set the preview output
// 步骤5:设置预览输出
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
// 步骤6:准备被配置的MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
-------------------------------
Prior to Android 2.2 (API Level 8), you must set the output format and encoding formats parameters directly, instead of using CamcorderProfile. This approach is demonstrated in the following code:
在Android 2.2(API级别8)开始,你必须直接地设置输出格式和编码格式参数,而非使用CamcorderProfile。这个方法被演示在以下代码中:
-------------------------------
// Step 3: Set output format and encoding (for versions prior to API Level 8)
// 步骤3:设置输出格式和编码(注:编码器)(对于版本在API级别8之前)
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
-------------------------------
The following video recording parameters for MediaRecorder are given default settings, however, you may want to adjust these settings for your application:
以下用于MediaRecorder的视频记录参数被给予默认的设置,然而,你可能希望为你的应用程序调整这些设置:
* setVideoEncodingBitRate()
* setVideoSize()
* setVideoFrameRate()
* setAudioEncodingBitRate()
* setAudioChannels()
* setAudioSamplingRate()
Starting and stopping MediaRecorder
启动和停止MediaRecorder
When starting and stopping video recording using the MediaRecorder class, you must follow a specific order, as listed below.
当使用MediaRecorder类启动和停止视频捕捉时,你必须遵循一个特定的顺序,正如下面所列举的那样。
1. Unlock the camera with Camera.unlock()
1. 用Camera.unlock()解锁照相机
2. Configure MediaRecorder as shown in the code example above
2. 配置MediaRecorder正如上面代码示例中所示
3. Start recording using MediaRecorder.start()
3. 使用MediaRecorder.start()开始记录
4. Record the video
4. 记录视频
5. Stop recording using MediaRecorder.stop()
5. 使用MediaRecorder.stop()停止记录
6. Release the media recorder with MediaRecorder.release()
6. 使用MediaRecorder.release()释放媒体记录器
7. Lock the camera using Camera.lock()
7. 使用Camera.lock()锁定照相机
The following example code demonstrates how to wire up a button to properly start and stop video recording using the camera and the MediaRecorder class.
以下示例代码演示如何接通一个按钮以使用照相机和MediaRecorder类正确地启动和停止视频记录。
-------------------------------
Note: When completing a video recording, do not release the camera or else your preview will be stopped.
注意:当完成一个视频记录时,不要释放照相机,否则你的预览将被停止。
-------------------------------
-------------------------------
private boolean isRecording = false;
// Add a listener to the Capture button
// 添加监听器到捕捉按钮
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isRecording) {
// stop recording and release camera
// 停止记录并释放照相机
mMediaRecorder.stop(); // stop the recording 停止记录
releaseMediaRecorder(); // release the MediaRecorder object 释放MediaRecorder对象
mCamera.lock(); // take camera access back from MediaRecorder 从MediaRecorder中取回照相机访问权
// inform the user that recording has stopped
// 告诉用户记录已经停止
setCaptureButtonText("Capture");
isRecording = false;
} else {
// initialize video camera
// 初始化视频照相机
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
// 照相机是可用和解锁的,MediaRecorder被准备,
// 现在你可以开始记录
mMediaRecorder.start();
// inform the user that recording has started
// 告知用户记录已经开始
setCaptureButtonText("Stop");
isRecording = true;
} else {
// prepare didn't work, release the camera
// 准备没有工作,释放照相机
releaseMediaRecorder();
// inform user
// 告诉用户
}
}
}
}
);
-------------------------------
-------------------------------
Note: In the above example, the prepareVideoRecorder() method refers to the example code shown in Configuring MediaRecorder. This method takes care of locking the camera, configuring and preparing the MediaRecorder instance.
注意:在上面的示例中,prepareVideoRecorder()方法引用在配置MediaRecorder中展示的示例代码。这个方法注意锁定照相机,配置和准备MediaRecorder实例。
-------------------------------
Releasing the camera
释放照相机
Cameras are a resource that is shared by applications on a device. Your application can make use of the camera after getting an instance of Camera, and you must be particularly careful to release the camera object when your application stops using it, and as soon as your application is paused (Activity.onPause()). If your application does not properly release the camera, all subsequent attempts to access the camera, including those by your own application, will fail and may cause your or other applications to be shut down.
照相机是一种资源,它被设备上的应用程序共享。你的应用程序可以在获得一个Camera实例后利用照相机,而且你必须特别小心地释放照相机对象,当你的应用程序停止使用它时,并且在你的应用程序被暂停时(Activity.onPause())就进行。如果你的应用程序不正确地释放照相机,那么所有随后访问照相机的尝试,包括你自己的应用程序的尝试,将失败并可能导致你的或其它应用程序被关闭。
To release an instance of the Camera object, use the Camera.release() method, as shown in the example code below.
为了释放一个Camera对象的实例,请使用Camera.release()方法,正如以下示例代码中所示。
-------------------------------
public class CameraActivity extends Activity {
private Camera mCamera;
private SurfaceView mPreview;
private MediaRecorder mMediaRecorder;
...
@Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first 如果你正在使用MediaRecorder,请首先释放它。
releaseCamera(); // release the camera immediately on pause event 在暂停事件上立刻释放照相机
}
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration 清除记录器配置
mMediaRecorder.release(); // release the recorder object 释放记录器对象
mMediaRecorder = null;
mCamera.lock(); // lock camera for later use 为后面的使用锁定照相机
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications 为其它应用程序释放照相机
mCamera = null;
}
}
}
-------------------------------
-------------------------------
Caution: If your application does not properly release the camera, all subsequent attempts to access the camera, including those by your own application, will fail and may cause your or other applications to be shut down.
警告:如果你的应用程序不正确地释放照相机,那么访问照相机的所有随后尝试,包括被你自己的应用程序作出的尝试,将失败并且可能导致你的或其它应用程序被关闭。
-------------------------------
-------------------------------
Saving Media Files
保存媒体文件
Media files created by users such as pictures and videos should be saved to a device's external storage directory (SD Card) to conserve system space and to allow users to access these files without their device. There are many possible directory locations to save media files on a device, however there are only two standard locations you should consider as a developer:
被用户创建的媒体文件诸如相片和视频应该被保存到一个设备的外部存储目录(SD卡)以节省系统空间并且允许用户不使用它们的设备来访问这些文件。在一台设备上有许多可能的目录路径来保存媒体文件,然而作为一个开发者来说只有两个标准位置你应该考虑:
* Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) - This method returns the standard, shared and recommended location for saving pictures and videos. This directory is shared (public), so other applications can easily discover, read, change and delete files saved in this location. If your application is uninstalled by the user, media files saved to this location will not be removed. To avoid interfering with users existing pictures and videos, you should create a sub-directory for your application's media files within this directory, as shown in the code sample below. This method is available in Android 2.2 (API Level 8), for equivalent calls in earlier API versions, see Saving Shared Files.
* Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)——这个方法返回用于保存相片和视频的标准、共享和建议的位置。这个目录是共享的(公共的),所以其它应用程序可以轻易的发现、读取、改变和删除保存在这个目录中的文件。如果你的应用程序被用户卸载,那么保存到这个目录的媒体文件将不被移除。为了避免干扰用户的现存相片和视频,你应该在这个目录中为你的应用程序的媒体文件创建一个子目录,正如下面的代码示例中所示。这个方法在Android 2.2(API级别8)中可用,想获得在较早API版本中等效的调用,请参见保存共享文件。
* Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) - This method returns a standard location for saving pictures and videos which are associated with your application. If your application is uninstalled, any files saved in this location are removed. Security is not enforced for files in this location and other applications may read, change and delete them.
* Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)——这个方法返回一个标准位置用于保存与你的应用程序关联的相片和视频。如果你的应用程序被卸载,保存在这个位置中的任意文件被移除。对于这个位置中的文件来说安全不被实施,而其它应用程序可能会读取、改变和删除它们。
The following example code demonstrates how to create a File or Uri location for a media file that can be used when invoking a device's camera with an Intent or as part of a Building a Camera App.
以下示例代码演示如何为一个媒体文件创建一个File或Uri位置,当用一个Intent调用一个设备的照相机或作为一个构建一个照相机应用的部分(注:步骤)时它可以被使用。
-------------------------------
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
/** 创建一个文件Uri以保存一个图片或视频 */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
/** 创建一个File以保存一个文件或视频 */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
// 为了安全,你应该在做这件时之前使用
// Environment.getExternalStorageState()检查SD卡被挂载。
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// 这个位置工作最佳,如果你希望被创建的图片在应用程序之间被共享
// 以及在你的应用已经被卸载后保留下来
// Create the storage directory if it does not exist
// 创建存储目录如果它不存在
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
// 创建一个媒体文件名
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
-------------------------------
-------------------------------
Note: Environment.getExternalStoragePublicDirectory() is available in Android 2.2 (API Level 8) or higher. If you are targeting devices with earlier versions of Android, use Environment.getExternalStorageDirectory() instead. For more information, see Saving Shared Files.
注意:Environment.getExternalStoragePublicDirectory()在Android 2.2(API级别8)或更高中可用。如果你正把目标定在带有较早版本Android的设备,那么请改为使用Environment.getExternalStorageDirectory()。想获得更多信息,参见保存共享文件。
-------------------------------
For more information about saving files on an Android device, see Data Storage.
想获得关于在一台Android设备上保存文件的更多信息,请参见数据存储。
-------------------------------
Camera Features
照相机特性
Android supports a wide array of camera features you can control with your camera application, such as picture format, flash mode, focus settings, and many more. This section lists the common camera features, and briefly discusses how to use them. Most camera features can be accessed and set using the through Camera.Parameters object. However, there are several important features that require more than simple settings in Camera.Parameters. These features are covered in the following sections:
Android提供一个广泛系列的照相机特性,你可以用你的照相机应用程序控制它们,诸如照片格式、闪光灯模式、对焦设置,以及许多其它东西。这个章节列举一般照相机特性,并且简要地讨论如何使用它们。大多数照相机特性可以使用贯穿前后的Camera.Parameters对象来被访问和设置。然而,有几个重要的特性不仅仅需要Camera.Parameters中的简单设置。这些特性在以下章节中被涵盖:
* Metering and focus areas
* 测量和焦点区域
* Face detection
* 脸部检测
* Time lapse video
* 慢速视频
For general information about how to use features that are controlled through Camera.Parameters, review the Using camera features section. For more detailed information about how to use features controlled through the camera parameters object, follow the links in the feature list below to the API reference documentation.
想获得关于如何使用通过Camera.Parameters而被控制的特性的一般信息,请回顾使用照相机特性章节。想获得关于如何使用通过照相机参数对象而被控制的特性的更详细信息,请跟随下面的特性列表中的链接跳到API参考文档。
Table 1. Common camera features sorted by the Android API Level in which they were introduced.
表1. 通用照相机特性,根据它们被引入的Android API级别排列。
-------------------------------
* Feature API Level Description
* 特性 API级别 描述
* Face Detection 14 Identify human faces within a picture and use them for focus, metering and white balance
* 脸部检测 14 在照片中标识人脸并使用它们用于聚焦,测量和白色平衡
* Metering Areas 14 Specify one or more areas within an image for calculating white balance
* 测量区域 14 在一个图片内标识一个或多个区域以计算白平衡
* Focus Areas 14 Set one or more areas within an image to use for focus
* 焦点区域 14 在图片内设置一个或多个区域以用于聚焦
* White Balance Lock 14 Stop or start automatic white balance adjustments
* 白平衡锁 14 停止或开始自动白平衡调整(注:白平衡在数码相机中是指色温)
* Exposure Lock 14 Stop or start automatic exposure adjustments
* 曝光锁 14 停止或开始自动曝光调整(注:曝光指摄影的过程中允许进入镜头照在感光媒体——胶片相机的底片或是数码照相机的图像传感器——上的光量)
* Video Snapshot 14 Take a picture while shooting video (frame grab)
* 视频快照 14 在抓拍视频时拍一张图片(注:这里的shoot video可能是Photo shoot的引申)(帧抓取)(注:影片撷取,另外,有一种专门的设备叫Frame grabber)
* Time Lapse Video 11 Record frames with set delays to record a time lapse video
* 慢速视频 11 记录设置延时的帧以记录一个慢速视频
* Multiple Cameras 9 Support for more than one camera on a device, including front-facing and back-facing cameras
* 多照相机 9 在设备上支持多于一个照相机,包括前置和后置照相机
* Focus Distance 9 Reports distances between the camera and objects that appear to be in focus
* 焦距 9 报告照相机与显得对齐焦点(注:清晰)的对象的距离。
* Zoom 8 Set image magnification
* 缩放 8 设置图片放大率
* Exposure Compensation 8 Increase or decrease the light exposure level
* 曝光补偿 8 增加或降低光线曝光级别
* GPS Data 5 Include or omit geographic location data with the image
* GPS数据 5 包含或忽略图片的地理位置数据。
* White Balance 5 Set the white balance mode, which affects color values in the captured image
* 白平衡 5 设置白平衡模式,它影响被捕捉图片的颜色值。
* Focus Mode 5 Set how the camera focuses on a subject such as automatic, fixed, macro or infinity
* 焦点模式 5 设置照相机如何聚焦在一个主体(注:主题)上诸如自动、固定、宏或无限。(注:这些应该是摄影术语,macro可能是指Macrophotography微距摄影,Macro是指镜筒比较长?infinity则可能是指焦点在无限远处)
* Scene Mode 5 Apply a preset mode for specific types of photography situations such as night, beach, snow or candlelight scenes
* 场景模式 5 为特定类型的照相环境应用一个维持模式诸如夜晚、沙滩、下雪或烛光场景。
* JPEG Quality 5 Set the compression level for a JPEG image, which increases or decreases image output file quality and size
* JPEG质量 5 为一个JPEG图片设置压缩级别,它增加或降低图片输出文件质量和大小
* Flash Mode 5 Turn flash on, off, or use automatic setting
* 闪光灯模式 5 打开闪光灯,关闭,或者使用自动设置
* Color Effects 5 Apply a color effect to the captured image such as black and white, sepia tone or negative.
* 颜色效果 5 应用一个颜色效果到被捕捉的图片诸如黑白,深褐色调,或反色。
* Anti-Banding 5 Reduces the effect of banding in color gradients due to JPEG compression
* 抗色彩带 5 降低由于JPEG压缩造成颜色渐变中的色彩带效果(注:banding,色彩带,又称色带,是电脑图学上色彩显示不准确的问题,一般是由色深低导致。详细见http://zh.wikipedia.org/wiki/%E8%89%B2%E5%BD%A9%E5%B8%B6。这里应该是指JPEG压缩太大而导致严重的彩色失真)
* Picture Format 1 Specify the file format for the picture
* 相片格式 1 指定相片的文件格式
* Picture Size 1 Specify the pixel dimensions of the saved picture
* 相片大小 1 指定被保存照片的像素尺寸
-------------------------------
-------------------------------
Note: These features are not supported on all devices due to hardware differences and software implementation. For information on checking the availability of features on the device where your application is running, see Checking feature availability.
注意:这些特性并不是在所有设备上都被支持,这是由于硬件不同和软件实现而导致的。想获得关于检查你的应用程序所运行在的设备上的特性可用性,请参见检查特性可用性。
-------------------------------
Checking feature availability
检查特性可用性
The first thing to understand when setting out to use camera features on Android devices is that not all camera features are supported on all devices. In addition, devices that support a particular feature may support them to different levels or with different options. Therefore, part of your decision process as you develop a camera application is to decide what camera features you want to support and to what level. After making that decision, you should plan on including code in your camera application that checks to see if device hardware supports those features and fails gracefully if a feature is not available.
当开始使用Android设备上的照相机特性时首先要理解的事情是,不是所有照相机特性在所有设备上都被支持。另外,支持一种特殊特性的设备可能支持它们到不同的级别或使用不同的选项。因此,当你开发一个照相机应用程序时你的决策处理的一部分是决定你想要支持什么照相机特性和到达什么级别。在作出那个决策之后,你应该打算在你的应用程序中包含代码,检查以了解设备硬件是否支持那些特性以及如果一个特性不可用时优雅地失败。
You can check the availabilty of camera features by getting an instance of a camera’s parameters object, and checking the relevant methods. The following code sample shows you how to obtain a Camera.Parameters object and check if the camera supports the autofocus feature:
你可以通过获得一个照相机参数对象的实例来检查照相机特性的可用性,和检查有关的方法。以下代码示例向你展示如何取得一个Camera.Parameters对象和检查照相机是否支持自动对焦特性:
-------------------------------
// get Camera parameters
// 获得Camera的参数
Camera.Parameters params = mCamera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
// Autofocus mode is supported
// 自动对焦模式被支持
}
-------------------------------
You can use the technique shown above for most camera features. The Camera.Parameters object provides a getSupported...(), is...Supported() or getMax...() method to determine if (and to what extent) a feature is supported.
你可以对大多数照相机特性使用上面所示的技术。Camera.Parameters对象提供一个getSupported...(),is...Supported()或getMax...()方法来确定一个特性是否被支持(和被支持到什么程度)。
If your application requires certain camera features in order to function properly, you can require them through additions to your application manifest. When you declare the use of specific camera features, such as flash and auto-focus, Google Play restricts your application from being installed on devices which do not support these features. For a list of camera features that can be declared in your app manifest, see the manifest Features Reference.
如果你的应用程序需要某些照相机特性以便正确地起作用,那么你可以通过添加到你的应用程序清单来需要它们。当你声明特定照相机特性的使用时,诸如闪光灯和自动对焦,Google Play限制你的应用程序不被安装在不支持这些特性的设备上。想获得一个可以被声明在你的应用清单中的照相机特性的列表,请参见清单特性参考手册。
Using camera features
使用照相机特性
Most camera features are activated and controlled using a Camera.Parameters object. You obtain this object by first getting an instance of the Camera object, calling the getParameters() method, changing the returned parameter object and then setting it back into the camera object, as demonstrated in the following example code:
大多数照相机特性使用一个Camera.Parameters对象来激活和控制。你取得这个对象,通过首先得到一个Camera对象的实例,调用getParameters()方法,改变返回的参数对象,然后设置它回到照相机对象,正如以下示例代码中所演示的那样:
-------------------------------
// get Camera parameters
// 获得Camera的参数
Camera.Parameters params = mCamera.getParameters();
// set the focus mode
// 设置焦点模式
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
// 设置Camera的参数
mCamera.setParameters(params);
-------------------------------
This technique works for nearly all camera features, and most parameters can be changed at any time after you have obtained an instance of the Camera object. Changes to parameters are typically visible to the user immediately in the application’s camera preview. On the software side, parameter changes may take several frames to actually take effect as the camera hardware processes the new instructions and then sends updated image data.
这项技术工作于几乎所有照相机特性,而且大多数参数可以在你已经取得一个Camera对象的实例后的任意时候被改变。对参数的改变通常对于用户来说在应用程序的照相机预览中是即时可见的。在软件方,参数的改变可能要花几帧来实际地生效,因为照相机硬件处理新的指令,然后才发送被更新的图片数据。
-------------------------------
Important: Some camera features cannot be changed at will. In particular, changing the size or orientation of the camera preview requires that you first stop the preview, change the preview size, and then restart the preview. Starting with Android 4.0 (API Level 14) preview orientation can be changed without restarting the preview.
重要:一些照相机特性不能被随意改变。特别地,改变照相机预览的大小或方向需要你首先停止预览,改变预览大小,然后重启预览。从Android 4.0(API级别14)开始预览方向可以被改变而不重启预览。
-------------------------------
Other camera features require more code in order to implement, including:
其它照相机特性需要更多代码来实现,包括:
* Metering and focus areas
* 测量和焦点区域
* Face detection
* 脸部检测
* Time lapse video
* 慢速视频
A quick outline of how to implement these features is provided in the following sections.
如何实现这些特性的一个快速概述在以下章节中被提供。
Metering and focus areas
测量和对焦区域
In some photographic scenarios, automatic focusing and light metering may not produce the desired results. Starting with Android 4.0 (API Level 14), your camera application can provide additional controls to allow your app or users to specify areas in an image to use for determining focus or light level settings and pass these values to the camera hardware for use in capturing images or video.
在一些摄影场景中,自动对焦(注:Autofocus,AF,自动变焦)和光线测量(注:Metering mode,测光模式,是指照相机通过测量主体的亮度以决定正确曝光的模式)可能不产生理想的结果。从Android 4.0(API级别14)开始,你的照相机应用程序可以提供额外的控制以允许你的应用或用户在图片(注:映像)中指定区域以用于确定焦点或光线等级设置,并且传递这些值给照相机硬件供捕捉图片或视频使用。
Areas for metering and focus work very similarly to other camera features, in that you control them through methods in the Camera.Parameters object. The following code demonstrates setting two light metering areas for an instance of Camera:
用于测量和对焦的区域与其它照相机特性非常类似地工作,因为你通过Camera.Parameters对象中的方法控制它们。以下代码演示为一个Camera实例设置两个光线测量区域:
-------------------------------
// Create an instance of Camera
// 创建一个Camera实例
mCamera = getCameraInstance();
// set Camera parameters
// 设置Camera的参数
Camera.Parameters params = mCamera.getParameters();
if (params.getMaxNumMeteringAreas() > 0){ // check that metering areas are supported 检查测量(注:仪表)区域被支持
List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>();
Rect areaRect1 = new Rect(-100, -100, 100, 100); // specify an area in center of image 在图片正中指定一个区域
meteringAreas.add(new Camera.Area(areaRect1, 600)); // set weight to 60% 设置权重为60%
Rect areaRect2 = new Rect(800, -1000, 1000, -800); // specify an area in upper right of image 在图片右上方指定一个区域
meteringAreas.add(new Camera.Area(areaRect2, 400)); // set weight to 40% 设置权重为40%
params.setMeteringAreas(meteringAreas);
}
mCamera.setParameters(params);
-------------------------------
The Camera.Area object contains two data parameters: A Rect object for specifying an area within the camera’s field of view and a weight value, which tells the camera what level of importance this area should be given in light metering or focus calculations.
Camera.Area对象包含两个数据参数:一个Rect对象用于指定照相机的视图域内的一个区域和一个权重值,它告诉照相机这个区域在光线测量或焦点计算时应该被给予什么等级的重要度。
The Rect field in a Camera.Area object describes a rectangular shape mapped on a 2000 x 2000 unit grid. The coordinates -1000, -1000 represent the top, left corner of the camera image, and coordinates 1000, 1000 represent the bottom, right corner of the camera image, as shown in the illustration below.
在Camera.Area对象中的一个Rect域描述一个矩形图形,它被映射在一个2000 x 2000单位的格(注:单元格)。坐标-1000, -1000代表照相机图片的左上角,而坐标1000, 1000代表照相机图片的右下角,正如下面的插图中所示。
(图1略:
红线:
-1000, -1000
1000, -1000
0, 0
-1000, 1000
蓝框:
Rect 333, 333, 667, 667
捕捉
)
Figure 1. The red lines illustrate the coordinate system for specifying a Camera.Area within a camera preview. The blue box shows the location and shape of an camera area with the Rect values 333,333,667,667.
图1. 红色线描绘用于在一个照相机预览内指定一个Camera.Area的坐标系。蓝色框展示一个照相机区域的位置和形状,它的Rect数值为333,333,667,667。
The bounds of this coordinate system always correspond to the outer edge of the image visible in the camera preview and do not shrink or expand with the zoom level. Similarly, rotation of the image preview using Camera.setDisplayOrientation() does not remap the coordinate system.
坐标系的范围总是对应在照相机预览中可视的图片的外边界,并且不使用缩放等级来缩小或扩大。同样,使用Camera.setDisplayOrientation()的图片预览旋转不重新映射坐标系。
Face detection
脸部检测
For pictures that include people, faces are usually the most important part of the picture, and should be used for determining both focus and white balance when capturing an image. The Android 4.0 (API Level 14) framework provides APIs for identifying faces and calculating picture settings using face recognition technology.
对于包含人的相片,脸部通常是相片的最重要部分,并且当捕捉一个图片时应该被用于确定焦点和白平衡。Android 4.0(API级别14)框架提供API用于使用脸部识别技术标识脸部和计算相片设置。
-------------------------------
Note: While the face detection feature is running, setWhiteBalance(String), setFocusAreas(List) and setMeteringAreas(List) have no effect.
注意:当脸部检测特性正在运行时,setWhiteBalance(String),setFocusAreas(List)和setMeteringAreas(List)没有效果。
-------------------------------
Using the face detection feature in your camera application requires a few general steps:
在你的照相机应用中使用脸部检测特性需要一些通常的步骤:
* Check that face detection is supported on the device
* 检查脸部检测在设备上被支持
* Create a face detection listener
* 创建一个脸部检测监听器
8 Add the face detection listener to your camera object
* 添加脸部检测监听器到你的照相机对象
* Start face detection after preview (and after every preview restart)
* 在预览后(并且在每次预览重启之后)启动脸部检测
The face detection feature is not supported on all devices. You can check that this feature is supported by calling getMaxNumDetectedFaces(). An example of this check is shown in the startFaceDetection() sample method below.
脸部检测特性不是在所有设备上都被支持。你可以通过调用getMaxNumDetectedFaces()检查这项特性是否被支持。这项检查的一个示例被展示在以下startFaceDetection()示例方法中。
In order to be notified and respond to the detection of a face, your camera application must set a listener for face detection events. In order to do this, you must create a listener class that implements the Camera.FaceDetectionListener interface as shown in the example code below.
为了被通知和响应一个脸部的检测,你的照相机应用程序必须为脸部检测事件设置一个监听器。为了做到这点,你必须创建一个监听器类,它实现Camera.FaceDetectionListener接口,正如以下示例代码中所示。
-------------------------------
class MyFaceDetectionListener implements Camera.FaceDetectionListener {
@Override
public void onFaceDetection(Face[] faces, Camera camera) {
if (faces.length > 0){
Log.d("FaceDetection", "face detected: "+ faces.length +
" Face 1 Location X: " + faces[0].rect.centerX() +
"Y: " + faces[0].rect.centerY() );
}
}
}
-------------------------------
After creating this class, you then set it into your application’s Camera object, as shown in the example code below:
在创建这个类后,然后你设置它进你的应用程序的Camera对象中,正如下面的示例代码中所示:
-------------------------------
mCamera.setFaceDetectionListener(new MyFaceDetectionListener());
-------------------------------
Your application must start the face detection function each time you start (or restart) the camera preview. Create a method for starting face detection so you can call it as needed, as shown in the example code below.
每次你启动(或重启)照相机预览时,你的应用程序必须启动脸部检测功能。为启动脸部检测创建一个方法,使你在需要时可以调用它,正如下面的示例代码中所示。
-------------------------------
public void startFaceDetection(){
// Try starting Face Detection
// 尝试开始脸部检测
Camera.Parameters params = mCamera.getParameters();
// start face detection only *after* preview has started
// 只在预览已经开始之后才开始脸部检测
if (params.getMaxNumDetectedFaces() > 0){
// camera supports face detection, so can start it:
mCamera.startFaceDetection();
}
}
-------------------------------
You must start face detection each time you start (or restart) the camera preview. If you use the preview class shown in Creating a preview class, add your startFaceDetection() method to both the surfaceCreated() and surfaceChanged() methods in your preview class, as shown in the sample code below.
每次你开始(或重启)照相机预览时你必须开始脸部检测。如果你使用在创建一个预览类中展示的预览类,请添加你的startFaceDetection()方法到你的预览类的surfaceCreated()和surfaceChanged()两个方法中,正如下面的示例代码所示。
-------------------------------
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
startFaceDetection(); // start face detection feature 启动脸部检测特性
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mHolder.getSurface() == null){
// preview surface does not exist
// 预览表面不存在
Log.d(TAG, "mHolder.getSurface() == null");
return;
}
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
// 忽略:尝试停止一个不存在的预览
Log.d(TAG, "Error stopping camera preview: " + e.getMessage());
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
startFaceDetection(); // re-start face detection feature 重新启动脸部检测特性
} catch (Exception e){
// ignore: tried to stop a non-existent preview
// 忽略:尝试停止一个不存在的预览
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
-------------------------------
-------------------------------
Note: Remember to call this method after calling startPreview(). Do not attempt to start face detection in the onCreate() method of your camera app’s main activity, as the preview is not available by this point in your application's the execution.
注意:记住在调用startPreview()之后调用这个方法。不要尝试在你的照相机应用的主活动的onCreate()方法中开始脸部检测,因为直至你的应用程序执行(注:此处多了the)中的这个点,预览是不可用的。
-------------------------------
Time lapse video
慢速视频
Time lapse video allows users to create video clips that combine pictures taken a few seconds or minutes apart. This feature uses MediaRecorder to record the images for a time lapse sequence.
慢速视频允许用户创建视频剪辑,它们组合起间隔几秒或几分钟拍摄的照片。这个特性使用MediaRecorder为一个慢速的序列而记录图片。
To record a time lapse video with MediaRecorder, you must configure the recorder object as if you are recording a normal video, setting the captured frames per second to a low number and using one of the time lapse quality settings, as shown in the code example below.
为了用MediaRecorder记录一个慢速视频,你必须配置recorder对象就像你正在记录一个普通视频那样,设置每秒捕捉帧数为一个低数值并且使用其中给一个慢速质量设置,正如下面的代码示例中所示。
-------------------------------
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
// 步骤3:设置一个CamcorderProfile(需要API级别8或更高)
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH));
...
// Step 5.5: Set the video capture rate to a low number
// 步骤5.5:设置视频捕捉速率为一个低数值
mMediaRecorder.setCaptureRate(0.1); // capture a frame every 10 seconds 每10秒捕捉1帧
-------------------------------
These settings must be done as part of a larger configuration procedure for MediaRecorder. For a full configuration code example, see Configuring MediaRecorder. Once the configuration is complete, you start the video recording as if you were recording a normal video clip. For more information about configuring and running MediaRecorder, see Capturing videos.
这些设置必须被执行作为MediaRecorder的一个更大配置过程的一部分。想获得一个完全配置代码示例,请参见配置MediaRecorder。一旦配置完成,你开始视频记录就像你正在记录一个普通视频剪辑那样。想获得关于配置和运行MediaRecorder的更多信息,请参见捕捉视频。
Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.
除特别说明外,本文在Apache 2.0下许可。细节和限制请参考内容许可证。
Android 4.0 r1 - 16 Apr 2012 17:06
-------------------------------
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
此页部分内容,是基于Android开源项目所创建和共享的工作,并且根据知识共享2.5署名许可证描述的条款来使用的修改版。
(本人翻译质量欠佳,请以官方最新内容为准,或者参考其它翻译版本:
* ソフトウェア技術ドキュメントを勝手に翻訳
http://www.techdoctranslator.com/android
* Ley's Blog
http://leybreeze.com/blog/
* 农民伯伯
http://www.cnblogs.com/over140/
* Android中文翻译组
http://androidbox.sinaapp.com/
)
发表评论
-
【翻译】(9-补丁2)电话簿提供者
2012-07-18 12:54 2394【翻译】(9-补丁2)电话簿提供者 see h ... -
【翻译】(8-补丁1)Android接口定义语言(AIDL)
2012-07-02 05:55 2920【翻译】(8-补丁1)Andro ... -
【翻译】(0)应用组件
2012-06-30 23:50 824【翻译】(0)应用组件 see http:// ... -
【翻译】(88)传感器
2012-05-21 21:25 1072【翻译】(88)传感器 ... -
【翻译】(87)复制与粘贴
2012-05-20 14:48 1922【翻译】(87)复制与粘贴 see http: ... -
【翻译】(86)音频捕捉
2012-05-16 15:14 1097【翻译】(86)音频捕捉 ... -
【翻译】(84)JetPlayer
2012-04-21 16:24 979【翻译】(84)JetPlayer see h ... -
【翻译】(83)媒体回放
2012-04-21 16:00 1855【翻译】(83)媒体回放 see http:/ ... -
【翻译】(82)多媒体与照相机
2012-04-18 23:05 949【翻译】(82)多媒体与照相机 see htt ... -
【翻译】(23-补丁3)构建无障碍服务
2012-04-18 21:57 1624【翻译】(23-补丁3)构 ... -
【翻译】(23-补丁2)使应用程序无障碍
2012-04-16 13:08 2094【翻译】(23-补丁2)使应用程序无障碍 see ... -
【翻译】(23-补丁1)无障碍
2012-04-11 22:38 908【翻译】(23-补丁1)无 ... -
【翻译】(81)Renderscript之运行时API参考手册
2012-04-11 22:13 1414【翻译】(81)Renderscript之运行时API参 ... -
【翻译】(80)Renderscript之计算
2012-04-09 14:09 1439【翻译】(80)Renderscript之计算 ... -
【翻译】(79)Renderscript之图形
2012-04-08 13:59 2862【翻译】(79)Renderscript之图形 ... -
【翻译】(78)Renderscript
2012-04-04 15:35 1434【翻译】(78)Renderscript see ... -
【翻译】(77)可绘画对象动画
2012-03-18 10:52 707【翻译】(77)可绘画对象动画 see htt ... -
【翻译】(76)视图动画
2012-03-18 10:04 803【翻译】(76)视图动画 see http:/ ... -
【翻译】(75)属性动画
2012-03-17 18:24 2503【翻译】(75)属性动画 see http:/ ... -
【翻译】(74)动画
2012-03-10 14:22 1019【翻译】(74)动画 ...
相关推荐
网页照相机,顾名思义,是指能够在网页上使用的虚拟照相机软件,它允许用户通过浏览器拍摄、编辑和分享照片,而无需安装额外的硬件设备。这类应用通常依赖于计算机的摄像头功能,为用户提供方便快捷的在线拍照体验,...
在Windows XP操作系统中,"xp自带照相机驱动"是指系统内置对数码相机或者摄像头的支持程序。XP系统虽然年代较为久远,但它仍然包含了基本的硬件驱动支持,包括用于连接和操作照相机的驱动程序。这些驱动是操作系统...
( 照相机类.docx )
高级照相机 信息 版 本 号:1.9.3 开 发 者:机锋网友 发布时间:2012-10-25 文件大小:1.51MB 高级照相机介绍 高级照相机(Camera Advance) 是 Android 平台上的一款功能比较实用的摄像头增强软件,它能够提供...
YT014-基于RT‐Thread的网络照相机.zipYT014-基于RT‐Thread的网络照相机.zipYT014-基于RT‐Thread的网络照相机.zipYT014-基于RT‐Thread的网络照相机.zipYT014-基于RT‐Thread的网络照相机.zipYT014-基于RT‐Thread...
照相机成像原理和构造 照相机成像原理和构造是摄影术的核心技术。照相机的镜头是一个凸透镜,来自物体的光经过凸透镜后,在胶卷上形成一个缩小、倒立的实像。胶卷上涂着一层感光物质,它能把这个像记录下来,经过显...
在嵌入式系统开发中,照相机实验是一个关键的领域,尤其对于硬件开发工程师和软件开发者来说,理解和掌握照相机的原理与应用至关重要。标题"照相机实验_照相机_源码"暗示了这是一个关于实践操作和源代码分析的学习...
在libGDX中,照相机(Camera)是用于控制场景视口和视角的重要工具。本文将深入探讨libGDX中的照相机使用,包括其基本概念、常见类型以及如何在实际项目中应用。 1. 基本概念: 照相机在libGDX中主要由`...
在Android开发中,直接调用系统照相机功能是一项常见的任务,尤其在开发摄影类或社交类应用时。这个“照相机例子”展示了如何在不依赖任何第三方库的情况下,利用原生API来启动并控制设备的照相机。让我们深入探讨...
本文将深入探讨如何使用JavaScript实现模仿照相机的Flash特效。 首先,让我们理解"模仿照相机"的概念。在网页上,模仿照相机功能意味着创建一个虚拟的相机界面,用户可以通过它进行拍照、预览、甚至应用各种滤镜...
在JavaScript的世界里,模拟照相机拍照效果是一种常见的交互式网页特效,它能让用户在网页上体验类似使用真实照相机的功能,如预览、调整参数、拍摄、滤镜等。这个特效通常结合HTML5的一些特性,如Canvas、Webcam ...
【简易照相机】项目是基于STM32微控制器实现的一款基本的照相机功能,它利用了OV7670这款常见的CMOS图像传感器,并通过DMA(Direct Memory Access,直接存储器访问)技术将捕获的图像数据高效地传输到SD卡中进行存储...
在这个“照相机测试.zip”文件中,我们可以推测这是关于使用STM32进行照相机功能的开发、调试或测试的资料。以下是围绕这个主题可能涉及的一些关键知识点: 1. **STM32硬件接口**:STM32通常通过SPI、I2C或MIPI CSI...
标题中的“照相机自制”指的是一个DIY项目,利用微控制器STM32来构建一个简易的照相机系统。这个项目的核心是通过编程实现基本的摄影功能,而不是依赖于传统的、复杂的相机硬件。STM32是一种广泛应用的微控制器,由...
真实模拟照相机的功能,用于教学和学习摄影
【电子照相机(VS2008)】是一款利用Visual Studio 2008开发的程序,它具备基本的拍照功能,并且允许用户在拍摄的照片上添加相框,增加了趣味性和个性化元素。根据描述,该程序有可能利用了DirectX或其他图形处理...
Delphi XE5 Android 调用照相机获取拍的照片 Delphi XE5 是一款功能强大且流行的开发环境,它提供了许多优秀的功能,包括对 Android 平台的支持。在 Android 平台上,Delphi XE5 提供了许多有用的组件和 API,允许...
3D全景照相机,安卓版的,下载用用就知道了
该资源为基于Stm32 开发的照相机实验,内含全部代码。 实验现象: 本实验开机的时候先检测字库,然后检测SD卡根目录是否存在PHOTO文件夹,如果不存在则创建,如果创建失败, 则报错(提示拍照功能不可用)。在找到...