Android開發:調用camera API 創建MediaRecorder

1. add  below three permission into AndroidManifest.xml file

  1. <uses-permission android:name"android.permission.CAMERA" /> 
  2. <uses-permission android:name"android.permission.RECORD_AUDIO" /> 
  3. <uses-permission android:name"android.permission.WRITE_EXTERNAL_STORAGE" /> 

2. get a camera instance

  1.  /** A safe way to get an instance of the Camera object. */ 
  2. public static Camera getCameraInstance(){ 
  3.     Camera c = null
  4.     try { 
  5.         c = Camera. open(); // attempt to get a Camera instance 
  6.     } 
  7.     catch (Exception e){ 
  8.         // Camera is not available (in use or does not exist) 
  9.     } 
  10.     return c; // returns null if camera is unavailable 
  11. }  

 

3. implement a preview for the user to preview the live image for the camera 
 
  1. public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { 
  2.     private SurfaceHolder mHolder; 
  3.     private Camera mCamera; 
  4.     
  5.     String TAG="CAMERAAPI"
  6.  
  7.     public CameraPreview(Context context, Camera camera) { 
  8.         super(context); 
  9.         mCamera = camera; 
  10.  
  11.         // Install a SurfaceHolder.Callback so we get notified when the 
  12.         // underlying surface is created and destroyed. 
  13.         mHolder = getHolder(); 
  14.         mHolder.addCallback( this); 
  15.         // deprecated setting, but required on Android versions prior to 3.0 
  16.         mHolder. setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
  17.     } 
  18.  
  19.     public void surfaceCreated(SurfaceHolder holder) { 
  20.         // The Surface has been created, now tell the camera where to draw the preview. 
  21.         try { 
  22.             mCamera.setPreviewDisplay(holder); 
  23.             mCamera.startPreview(); 
  24.         } catch (IOException e) { 
  25.             Log. d(TAG, "Error setting camera preview: " + e.getMessage()); 
  26.         } 
  27.     } 
  28.  
  29.     public void surfaceDestroyed(SurfaceHolder holder) { 
  30.         // empty. Take care of releasing the Camera preview in your activity. 
  31.     } 
  32.  
  33.     public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 
  34.         // If your preview can change or rotate, take care of those events here. 
  35.         // Make sure to stop the preview before resizing or reformatting it. 
  36.  
  37.         if (mHolder .getSurface() == null){ 
  38.           // preview surface does not exist 
  39.           return
  40.         } 
  41.  
  42.         // stop preview before making changes 
  43.         try { 
  44.             mCamera.stopPreview(); 
  45.         } catch (Exception e){ 
  46.           // ignore: tried to stop a non-existent preview 
  47.         } 
  48.  
  49.         // set preview size and make any resize, rotate or 
  50.         // reformatting changes here 
  51.  
  52.         // start preview with new settings 
  53.         try { 
  54.             mCamera.setPreviewDisplay( mHolder); 
  55.             mCamera.startPreview(); 
  56.  
  57.         } catch (Exception e){ 
  58.             Log. d(TAG, "Error starting camera preview: " + e.getMessage()); 
  59.         } 
  60.     } 
4.initialize MediaRecorder for video recording
 
  1.  private boolean prepareVideoRecorder(){ 
  2.  
  3.     mCamera = getCameraInstance(); 
  4.     mMediaRecorder = new MediaRecorder(); 
  5.  
  6.     // Step 1: Unlock and set camera to MediaRecorder 
  7.     mCamera.unlock(); 
  8.     mMediaRecorder.setCamera(mCamera ); 
  9.  
  10.     // Step 2: Set sources 
  11.     mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); 
  12.     mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); 
  13.  
  14.     // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) 
  15.     mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile. QUALITY_HIGH)); 
  16.  
  17.     // Step 4: Set output file 
  18.     mMediaRecorder.setOutputFile(getOutputMediaFile( MEDIA_TYPE_VIDEO).toString()); 
  19.  
  20.     // Step 5: Set the preview output 
  21.     mMediaRecorder.setPreviewDisplay(mPreview .getHolder().getSurface()); 
  22.  
  23.     // Step 6: Prepare configured MediaRecorder 
  24.     try { 
  25.         mMediaRecorder.prepare(); 
  26.     } catch (IllegalStateException e) { 
  27.         Log. d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage()); 
  28.         releaseMediaRecorder(); 
  29.         return false ; 
  30.     } catch (IOException e) { 
  31.         Log. d(TAG, "IOException preparing MediaRecorder: " + e.getMessage()); 
  32.         releaseMediaRecorder(); 
  33.         return false ; 
  34.     } 
  35.     return true ; 

 

5.listen for the user operation to start or stop recording, the complete code for MediaRecorder is as below,remember to release the camera and MediaRecord when finished using it.
 
  1. public class MediaRecorderActivity extends Activity { 
  2.         
  3.         
  4.         public static final int MEDIA_TYPE_IMAGE = 1
  5.         public static final int MEDIA_TYPE_VIDEO = 2
  6.  
  7.     private Camera mCamera; 
  8.     private CameraPreview mPreview; 
  9.     private MediaRecorder mMediaRecorder; 
  10.     String TAG="CAMERAAPI"
  11.     boolean isRecording=false ; 
  12.     
  13.  
  14.     @Override 
  15.     public void onCreate(Bundle savedInstanceState) { 
  16.         super.onCreate(savedInstanceState); 
  17.         setContentView(R.layout. main); 
  18.         
  19.         mCamera = getCameraInstance(); 
  20. //        // Create our Preview view and set it as the content of our activity. 
  21.         mPreview = new CameraPreview(this, mCamera); 
  22.         FrameLayout preview = (FrameLayout) findViewById(R.id. camera_preview); 
  23.         preview.addView( mPreview); 
  24.                
  25.         Button captureButton = (Button) findViewById(id. button_capture); 
  26.         captureButton.setOnClickListener( new CaptureButtonOnClickListener()); 
  27.     } 
  28.     
  29.        
  30.     public class CaptureButtonOnClickListener implements View.OnClickListener{ 
  31.  
  32.         public void onClick(View v) { 
  33.                
  34.               Button captureButton = (Button)v; 
  35.                
  36.             if (isRecording ) { 
  37.                 // stop recording and release camera 
  38.                 mMediaRecorder.stop();  // stop the recording 
  39.                 releaseMediaRecorder(); // release the MediaRecorder object 
  40.                 mCamera.lock();         // take camera access back from MediaRecorder 
  41.  
  42.                 // inform the user that recording has stopped 
  43.                 captureButton.setText( "Capture"); 
  44.                 
  45.                 isRecording = false ; 
  46.             } else { 
  47.                
  48.                try
  49.                 // initialize video camera 
  50.                 if (prepareVideoRecorder()) { 
  51.                     // Camera is available and unlocked, MediaRecorder is prepared, 
  52.                     // now you can start recording 
  53.                     mMediaRecorder.start(); 
  54.  
  55.                     // inform the user that recording has started 
  56.                     captureButton.setText( "Stop"); 
  57.                     isRecording = true ; 
  58.                 } else { 
  59.                     // prepare didn't work, release the camera 
  60.                     releaseMediaRecorder(); 
  61.                     // inform user 
  62.                 } 
  63.                 
  64.               } catch(Exception ex){ 
  65.                       
  66.                      System. out.println(ex.toString()); 
  67.                      ex.printStackTrace(); 
  68.               } 
  69.             } 
  70.         }      
  71.     } 
  72.     /** A safe way to get an instance of the Camera object. */ 
  73.     public static Camera getCameraInstance(){ 
  74.         Camera c = null
  75.         try { 
  76.             c = Camera. open(); // attempt to get a Camera instance 
  77.         } 
  78.         catch (Exception e){ 
  79.             // Camera is not available (in use or does not exist) 
  80.         } 
  81.         return c; // returns null if camera is unavailable 
  82.     } 
  83.     
  84.     
  85.     
  86.         /** Create a File for saving an image or video */ 
  87.         private static File getOutputMediaFile(int type){ 
  88.            // To be safe, you should check that the SDCard is mounted 
  89.            // using Environment.getExternalStorageState() before doing this. 
  90.  
  91.            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( 
  92.                      Environment. DIRECTORY_PICTURES), "MyCameraApp" ); 
  93.            // This location works best if you want the created images to be shared 
  94.            // between applications and persist after your app has been uninstalled. 
  95.  
  96.            // Create the storage directory if it does not exist 
  97.            if (! mediaStorageDir.exists()){ 
  98.                if (! mediaStorageDir.mkdirs()){ 
  99.                    Log. d("MyCameraApp""failed to create directory"); 
  100.                    return null ; 
  101.                } 
  102.            } 
  103.  
  104.            // Create a media file name 
  105.            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss" ).format(new Date()); 
  106.            File mediaFile; 
  107.            if (type == MEDIA_TYPE_IMAGE){ 
  108.                mediaFile = new File(mediaStorageDir.getPath() + File.separator + 
  109.                "IMG_"+ timeStamp + ".jpg" ); 
  110.            } else if (type == MEDIA_TYPE_VIDEO) { 
  111.                mediaFile = new File(mediaStorageDir.getPath() + File.separator + 
  112.                "VID_"+ timeStamp + ".mp4" ); 
  113.            } else { 
  114.                return null ; 
  115.            } 
  116.  
  117.            return mediaFile; 
  118.        } 
  119.         
  120.           @Override 
  121.            protected void onPause() { 
  122.                super.onPause(); 
  123.                releaseMediaRecorder();       // if you are using MediaRecorder, release it first 
  124.                releaseCamera();              // release the camera immediately on pause event 
  125.            } 
  126.  
  127.            private void releaseCamera(){ 
  128.                if (mCamera != null){ 
  129.                    mCamera.release();        // release the camera for other applications 
  130.                    mCamera = null
  131.                } 
  132.            } 
  133.   
  134.            private void releaseMediaRecorder(){ 
  135.                if (mMediaRecorder != null) { 
  136.                    mMediaRecorder.reset();   // clear recorder configuration 
  137.                    mMediaRecorder.release(); // release the recorder object 
  138.                    mMediaRecorder = null ; 
  139.                    mCamera.lock();           // lock camera for later use 
  140.                } 
  141.            }    

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章