Android Video Recording

Source: Internet
Author: User

Android Video Recording

We generally extract data directly from the camera and microphone, encode the data, and save it as a file. Android video recording requires MediaRecorder. In addition to recording audio, MediaRecorder can also be used to record videos.

As shown in:

During the recording process, you can see the recording time at the top of the screen, and the last one is to stop recording the video.

 

The recorded video can be found on the SD card of the mobile phone, as shown in:

 

Video recording procedure:

1) Call setVideoEncoder (), setVideoEncodingBitRate (intbitRate), and setVideoFrameRate of the MediaRecorder object to set the encoding format, encoding bit rate, and frames per second of the recorded video, these parameters can control the quality and file size of the recorded video. Generally, the better the video quality, the larger the video file.

2) Call the setPreviewDisplay (Surfacesv) method of MediaRecorder to set which SurfaceView is used to display the video preview.

The instance uses MediaRecorder to record a video:

 

 

Import android. annotation. suppressLint; import android. app. activity; import android. graphics. pixelFormat; import android. hardware. camera; import android. media. mediaRecorder; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import android. view. *; import android. view. surfaceHolder. callback; import android. widget. button; import android. widget. linearLayout; import android. widget. TextView; import android. widget. toast; import java. io. file; import java. text. simpleDateFormat; import java. util. calendar; @ SuppressLint (SimpleDateFormat) public class MyActivity extends Activity implements Callback {private SurfaceView mSurfaceview; private Button mBtnStartStop; // start to stop recording press private boolean mStartedFlg = false; private MediaRecorder mRecorder; // private SurfaceHolder mSurfaceHolder of the video recording class ;// Display video private Camera camera; private TextView timeView; // display the recording time on the top of the screen private int time = 0; @ SuppressLint (HandlerLeak) private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case 1: // start recording timeView. setText (time + s); break; case 2: // recording ends in 8 s mRecorder. stop (); mRecorder. reset (); // You can reuse the object bymBtnStartStop. setText (Start); mStartedFlg = fals E; time = 0; timeView. setText (time + s); break; case 3: // health check End time = 0; timeView. setText (time + s); break ;};};@ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); // remove the title bar getWindow (). setFlags (WindowManager. layoutParams. FLAG_FULLSCREEN, WindowManager. layoutParams. FLAG_FULLSCREEN); // set full screen getWindow (). setFormat (PixelFormat. TRANSLUCENT); // select to support the TRANSLUCENT mode, which is used in a surfaceview activity. SetContentView (R. layout. main); // load the layout timeView = (TextView) findViewById (R. id. time); mSurfaceview = (SurfaceView) findViewById (R. id. surfaceview); mBtnStartStop = (Button) findViewById (R. id. btn); mBtnStartStop. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubif (! MStartedFlg) {// start if (mRecorder = null) {mRecorder = new MediaRecorder (); // create mediarecorder object} try {camera. unlock (); mRecorder. setCamera (camera); mRecorder. setAudioSource (MediaRecorder. audioSource. CAMCORDER); // these two items need to be placed before setOutputFormat mRecorder. setVideoSource (MediaRecorder. videoSource. CAMERA); // set the recorded video source to Camera (CAMERA) mRecorder. setOrientationHint (90); // Set output file formatmRecorder. setOutputFormat (M EdiaRecorder. outputFormat. MPEG_4); // set the video Encapsulation Format THREE_GPP to 3gp after recording. MPEG_4 is mp4 // these two items need to be placed after setOutputFormat mRecorder. setAudioEncoder (MediaRecorder. audioEncoder. AMR_NB); mRecorder. setVideoEncoder (MediaRecorder. videoEncoder. MPEG_4_SP); // sets the recorded video encoding h263mRecorder. setVideoSize (800,480); // sets the video recording resolution. It must be placed behind the encoding and format. Otherwise, the error message "mRecorder. setVideoFrameRate (30)" is returned. // you can specify the recorded video frame rate. It must be placed behind the encoding and format. Otherwise, the error message "mRecorder" is returned. setMaxDuration (8000); // sets the maximum recording time (mRecorder. setPreviewDisplay (mSurfaceHolder. getSurface (); // Set output file pathString path = getSDPath (); if (path! = Null) {File dir = new File (path +/recordtest); if (! Dir. exists () {dir. mkdir ();} path = dir +/+ getDate () +. mp4; Toast. makeText (MyActivity. this, path, Toast. LENGTH_LONG ). show (); mRecorder. setOutputFile (path); mRecorder. prepare (); // prepare to record mRecorder. start (); // start recording new Thread (new Runnable () {@ Overridepublic void run () {while (time <8) {try {time ++; Thread. sleep (1000); handler. sendEmptyMessage (1);} catch (InterruptedException e) {// TODO Auto-generated catc H blocke. printStackTrace () ;}} handler. sendEmptyMessage (2 );}}). start (); mStartedFlg = true; mBtnStartStop. setText (Stop) ;}} catch (Exception e) {e. printStackTrace () ;}} else {// stopif (mStartedFlg) {try {mRecorder. stop (); mRecorder. reset (); // You can reuse the object by // going back to // setAudioSource () stepmBtnStartStop. setText (Start); handler. sendEmptyMessageDelayed (3, 1000);} catch (Exception e) {e. PrintStackTrace () ;}} mStartedFlg = false; // Set button status flag }}); SurfaceHolder holder = mSurfaceview. getHolder (); // get holderholder. addCallback (this); // Add holder to the callback interface holder. setType (SurfaceHolder. SURFACE_TYPE_PUSH_BUFFERS); // setType must be set to avoid errors .} /*** use the time to name the video ** @ return */public static String getDate () {Calendar ar ca = Calendar ar. getInstance (); SimpleDateFormat sdf = new SimpleDateFormat (yyyyMMddh Hmmss); String date = sdf. format (ca. getTimeInMillis (); return date;}/*** get SD path ** @ return */public String getSDPath () {File sdDir = null; boolean sdCardExist = Environment. getExternalStorageState (). equals (android. OS. environment. MEDIA_MOUNTED); // determines whether the SD card exists if (sdCardExist) {sdDir = Environment. getExternalStorageDirectory (); // get the directory with the path // Toast. makeText (this, sdDir. toString (), Toast. LENGTH_LONG ). show (); Return sdDir. toString ();} else {Toast. makeText (this, no SD card, Toast. LENGTH_LONG ). show () ;}return null ;}@ Overridepublic void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {camera = Camera. open (); // get the Camera instance try {camera. setPreviewDisplay (holder); mSurfaceview. setLayoutParams (new LinearLayout. layoutParams (width, height);} catch (Exception e) {// if an Exception occurs, release the Camera object camera. relea Se ();} camera. setDisplayOrientation (90); // sets the portrait screen of the Preview Video from time to time. // starts the preview function camera. startPreview (); // set holder, which is the holder that is obtained in onCreate and assigned to mSurfaceHoldermSurfaceHolder = holder;} @ Overridepublic void surfaceCreated (SurfaceHolder holder) {// set holder, which is the holder that is obtained in onCreate and assigned to mSurfaceHoldermSurfaceHolder = holder;} @ Overridepublic void surfaceDestroyed (SurfaceHolder holder) {// TODO Auto-generated me When thod stub // surfaceDestroyed is used, the object is set to nullmSurfaceview = null; mSurfaceHolder = null; if (mRecorder! = Null) {mRecorder. release (); // Now the object cannot be reusedmRecorder = null;} if (camera! = Null) {camera. release (); camera = null ;}}}
The XML layout file is:

 



 

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.