android Camera

来源:互联网 发布:网络语言暴力的著作 编辑:程序博客网 时间:2024/06/05 08:56

use of camera hardware and other related features.

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
/** A basic Camera preview class */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.        mHolder = getHolder();        mHolder.addCallback(this);        // deprecated setting, but required on Android versions prior to 3.0        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.        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.    }    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());        }    }}
>

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 theCamera.lock() and Camera.unlock() calls to allow MediaRecorder access to the camera hardware, in addition to the Camera.open() and Camera.release() calls.

Note: Starting with Android 4.0 (API level 14), the Camera.lock() and Camera.unlock() calls are managed for you automatically.

>

The following example code demonstrates how to properly configure and prepare the MediaRecorder class for video recording.

private boolean prepareVideoRecorder(){    mCamera = getCameraInstance();    mMediaRecorder = new MediaRecorder();    // Step 1: Unlock and set camera to MediaRecorder    mCamera.unlock();    mMediaRecorder.setCamera(mCamera);    // Step 2: Set sources    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));    // Step 4: Set output file    mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());    // Step 5: Set the preview output    mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());    // Step 6: Prepare configured 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:

    // Step 3: Set output format and encoding (for versions prior to API Level 8)    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);

>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.

>

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.

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 */private static Uri getOutputMediaFileUri(int type){      return Uri.fromFile(getOutputMediaFile(type));}/** Create a File for saving an image or video */private static File getOutputMediaFile(int type){    // To be safe, you should check that the SDCard is mounted    // using Environment.getExternalStorageState() before doing this.    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, useEnvironment.getExternalStorageDirectory() instead. For more information, see Saving Shared Files.

0 0