My Android advanced tutorial ------ & gt; small example of Android Video Recording

Source: Internet
Author: User


Object and coordination with class. When recording video with , you must manage the  and calls to allow  access to the camera hardware, in addition to the and  calls.

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

    Open Camera - Use the  to get an instance of the camera object.
  1. Connect Preview - Prepare a live camera image preview by connecting a  to the camera using.
  2. Start Preview - Call  to begin displaying the live camera images.
  3. Start Recording Video - The following steps must be completed in order to successfully record video:
      Unlock the Camera - Unlock the camera for use by   by calling .
    1. Configure MediaRecorder - Call in the following  methods in this order. For more information, see the  reference documentation.
         - Set the camera to be used for video capture, use your application's current instance of .
      1.  - Set the audio source, use .
      2.  - Set the video source, use .
      3.  method, and get a profile instance using . For versions of Android prior to 2.2, you must set the video output format and encoding parameters:
           - Set the output format, specify the default setting or .
        1.  - Set the sound encoding type, specify the default setting or.
        2.  - Set the video encoding type, specify the default setting or.
      4.  - Set the output file, use  from the example method in the Saving Media Files section.
      5.  - Specify the  preview layout element for your application. Use the same object you specified for Connect Preview.

      Caution: You must call these  configuration methods in this order, otherwise your application will encounter errors and the recording will fail.

    2. Prepare MediaRecorder - Prepare the  with provided configuration settings by calling.
    3. Start MediaRecorder - Start recording video by calling .
  4. Stop Recording Video - Call the following methods in order, to successfully complete a video recording:
      Stop MediaRecorder - Stop recording video by calling  .
    1. Reset MediaRecorder - Optionally, remove the configuration settings from the recorder by calling.
    2. Release MediaRecorder - Release the  by calling .
    3. Lock the Camera - Lock the camera so that future  sessions can use it by calling. Starting with Android 4.0 (API level 14), this call is not required unless the call fails.
  5. Stop the Preview - When your activity has finished using the camera, stop the preview using.
  6. Release Camera - Release the camera so that other applications can use it by calling .

Note: It is possible to use  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.

Tip: If your application is typically used for recording video, set  to  prior to starting your preview. This setting can help reduce the time it takes to start recording.

 APIs if supported by the device hardware.

Note: The Android Emulator does not have the ability to capture audio, but actual devices are likely to provide these capabilities.

    .
  1. . You will probably want to use.
  2. .
  3. .
  4. .
  5.  on the MediaRecorder instance.
  6. .
  7. .
  8.  on it. Calling is always recommended to free the resource immediately.



<! -- Frame layout --> <FrameLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <! -- Used to display the screen --> <SurfaceView android: id = "@ + id/surfaceView" android: layout_width = "fill_parent" android: layout_height = "fill_parent"/> <! -- Relative layout: this interface is not displayed by default. It is displayed when you touch the screen --> <RelativeLayout android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: visibility = "gone" android: id = "@ + id/buttonlayout"> <! -- Burn Button --> <Button android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignParentRight = "true" android: layout_alignParentBottom = "true" android: layout_marginRight = "10dp" android: text = "@ string/recoderbutton" android: onClick = "recoder" android: id = "@ + id/recoderbutton"/> <! -- Stop Button --> <Button android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_toLeftOf = "@ id/recoderbutton" android: layout_alignTop = "@ id/recoderbutton" android: layout_marginRight = "30dp" android: text = "@ string/stopbutton" android: onClick = "stop" android: id = "@ + id/stopbutton" android: enabled = "false"/> </RelativeLayout> </FrameLayout>


<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "hello"> Hello World, RecoderActivity! </String> <string name = "app_name"> video burning example </string> <string name = "recoderbutton"> burning </string> <string name = "stopbutton"> stop </string> <string name = "noSDcard"> no memory card is found on the mobile phone! Please insert a mobile phone memory card and start the app </string> <string name = "maxDuration"> the maximum recording time has been reached </string> </resources>


Package cn. oyp. recoder; import java. io. file; import android. app. activity; import android. content. pm. activityInfo; import android. media. mediaRecorder; import android. media. mediaRecorder. onInfoListener; import android. OS. bundle; import android. OS. environment; import android. view. motionEvent; import android. view. surfaceHolder; import android. view. surfaceView; import android. view. view; import android. view. viewGrou P; import android. view. window; import android. view. windowManager; import android. widget. button; import android. widget. relativeLayout; import android. widget. toast; public class RecoderActivity extends Activity {// used to display the picture private SurfaceView surfaceView; // the layout of the burning and stopping buttons is private RelativeLayout buttonlayout; // The Burning Button private Button recoderbutton; // stop Button private Button stopbutton; // media burning object private MediaRecorder mediaRe Corder;/** Called when the activity is first created. * // @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // The Window effect is the Untitled requestWindowFeature (Window. FEATURE_NO_TITLE); // sets the full screen getWindow () of the window (). setFlags (WindowManager. layoutParams. FLAG_FULLSCREEN, WindowManager. layoutParams. FLAG_FULLSCREEN); // sets the screen to display as a horizontal setRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_LANDSCAPE ); SetContentView (R. layout. main); buttonlayout = (RelativeLayout) this. findViewById (R. id. buttonlayout); recoderbutton = (Button) this. findViewById (R. id. recoderbutton); stopbutton = (Button) this. findViewById (R. id. stopbutton); surfaceView = (SurfaceView) this. findViewById (R. id. surfaceView); // The obtained image is directly output to the surfaceView on the screen. getHolder (). setType (SurfaceHolder. SURFACE_TYPE_PUSH_BUFFERS); // screen resolution surfaceView. getHol Der (). setFixedSize (176,144); // keep the screen highlighted surfaceView. getHolder (). setKeepScreenOn (true);} // click the burn button to handle public void recoder (View v) {try {// determine whether the SD card if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// Save the burned video to the SD card File videoFile = new File (Environment. getExternalStorageDirectory (), System. currentTimeMillis () + ". 3gp "); mediaRecorder = new MediaRecorder (); // set the sound collection source to the microphone mediaR Ecorder. setAudioSource (MediaRecorder. audioSource. MIC); // sets the video capture source from the camera mediaRecorder. setVideoSource (MediaRecorder. videoSource. CAMERA); // set the output format to 3gpmediaRecorder. setOutputFormat (MediaRecorder. outputFormat. THREE_GPP); // sets the video size mediaRecorder. setVideoSize (surfaceView. getWidth (), surfaceView. getHeight (); // set the number of captured images per second to 5 mediaRecorder. setVideoFrameRate (5); // sets the Audio Encoding mediaRecorder. setAudioEncoder (MediaRecorde R. audioEncoder. AMR_NB); // sets the video encoding mediaRecorder. setAudioEncoder (MediaRecorder. videoEncoder. h264); // sets the maximum video duration mediaRecorder. setMaxDuration (10000); mediaRecorder. setOnInfoListener (new OnInfoListener () {@ Overridepublic void onInfo (MediaRecorder mr, int what, int extra) {if (what = MediaRecorder. MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {Toast. makeText (getApplicationContext (), R. string. maxDuration, Toa St. LENGTH_LONG). show (); if (mediaRecorder! = Null) {mediaRecorder. stop (); mediaRecorder. release (); mediaRecorder = null ;}}}); // sets the path for saving the burned video to mediaRecorder. setOutputFile (videoFile. getAbsolutePath (); // sets the preview to display mediaRecorder. setPreviewDisplay (surfaceView. getHolder (). getSurface (); // prepare mediaRecorder as expected. prepare (); // starts to burn mediaRecorder. start ();} else {Toast. makeText (getApplicationContext (), R. string. noSDcard, Toast. LENGTH_LONG ). show () ;}} catch (effectio N e) {e. printStackTrace ();} // do not click recoderbutton for the burn button. setEnabled (false); // click the stop button. setEnabled (true);} // click the stop button to handle public void stop (View v) {// stop burning and release the resource if (mediaRecorder! = Null) {mediaRecorder. stop (); mediaRecorder. release (); mediaRecorder = null;} // click recoderbutton to burn. setEnabled (true); // the stop button cannot be clicked. setEnabled (false);}/** display the focus and photo button layout when you touch the screen */@ Overridepublic boolean onTouchEvent (MotionEvent event) {if (event. getAction () = MotionEvent. ACTION_DOWN) {buttonlayout. setVisibility (ViewGroup. VISIBLE); return true;} return super. onTouchEvent (event );}}


<? Xml version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "cn. oyp. recoder "android: versionCode =" 1 "android: versionName =" 1.0 "> <uses-sdk android: minSdkVersion =" 8 "/> <! -- CAMERA permission --> <uses-permission android: name = "android. permission. CAMERA"/> <! -- Recording audio permission --> <uses-permission android: name = "android. permission. RECORD_AUDIO"/> <! -- Create and delete file permissions on the SD card --> <uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS"/> <! -- Permission to write data to the SD card --> <uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE "/> <application android: icon =" @ drawable/icon "android: label =" @ string/app_name "> <activity android: name = ". recoderActivity "android: label =" @ string/app_name "android: screenOrientation =" landscape "> <intent-filter> <action android: name =" android. intent. action. MAIN "/> <category android: name =" android. intent. category. LAUNCHER "/> </intent-filter> </activity> </application> </manifest>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.