Android uses the Mediarecorder class for recording video _android

Source: Internet
Author: User
Tags prepare

The cloud Habitat community reminds you to use the Mediarecorder recording set code steps must be set in the order specified by the API, otherwise the error

Steps are:

1, set the video source, audio source, that is, input source

2. Set Output format

3, set the audio and video coding format

First, look at the layout file, here is a surfaceview, this is a drawing container, you can directly from the memory or DMA hardware interface to obtain image data,

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android". Com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orient" ation= "vertical" tools:context= "Com.xqx.mediarecorder.app.WorkRecorder" > <!--start recording button--> <butt On android:id= "@+id/startrecord" android:layout_width= "wrap_content" android:layout_height= "Wrap_c" Ontent "android:onclick=" Btnstartrecord "android:text=" Start recording/> <button android: Id= "@+id/stoprecord" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andr oid:onclick= "Btnstoprecord" android:text= stop recording "/> <surfaceview android:id=" @+id/surview "Android:layout_width=" match_parent "android:layout_height=" match_parent "/> </LinearLayout>

Second, the Activity code

1, first look at the member variable

 Start recording, stop recording button
  private button startrecord,stoprecord;
  Show preview of Surfaceview
  private Surfaceview Surfaceview;
  tag to determine whether
  Boolean isrunning = False is currently being recorded;
  Recording class
  private Mediarecorder recorder;
  Store files
  private file savefile;

2, some initialization in the OnCreate () method

Startrecord = (Button) Findviewbyid (R.id.startrecord);
Stoprecord = (Button) Findviewbyid (R.id.stoprecord);
Surfaceview = (Surfaceview) Findviewbyid (R.id.surview);
OnCreate () initialization, must not start recording at first, so stop button is not clickable
Stoprecord.setenabled (FALSE);
Set surface do not need to maintain their own buffers
Surfaceview.getholder (). SetType (Surfaceholder.surface_type_push_buffers);
Set resolution
Surfaceview.getholder (). Setfixedsize (320, 280);
Setting this component does not allow the screen to automatically close
Surfaceview.getholder (). Setkeepscreenon (True);

3, now watch the "Start recording" listening event

----3.1

 Create Mediarecorder object
  recorder = new Mediarecorder ();
  Recorder.reset ();

----3.2 Set three steps, fixed sequentially

1. Set up acquisition sound
Recorder.setaudiosource (MediaRecorder.AudioSource.MIC);
Setting up the collection image
Recorder.setvideosource (MediaRecorder.VideoSource.CAMERA);
2. Set the video, audio output format
recorder.setoutputformat (MediaRecorder.OutputFormat.THREE_GPP);
3. Set the audio encoding format
recorder.setaudioencoder (MediaRecorder.AudioEncoder.DEFAULT);
Sets the encoding format of the image
Recorder.setvideoencoder (MediaRecorder.VideoEncoder.DEFAULT);

----3.3 Other optional settings, see the API for more

Set Stereo
recorder.setaudiochannels (2);
Set maximum video time unit: Millisecond
recorder.setmaxduration (600000);
Sets the size of the maximum recording unit, byte
recorder.setmaxfilesize (1024*1024);
How much data bit
recorder.setaudioencodingbitrate (128) The audio contains in one second;
Set selection angle, clockwise direction, because the default is reverse 90 degrees, so that the image is normal display, here is set to watch the video from the perspective of
recorder.setorientationhint ();
Set the video resolution
Recorder.setvideosize (176, 144);

----3.4 Set the file storage path, here is simple, the actual development needs to determine whether there is external storage, whether there is a target directory, whether there is a file with the same name, and so on

Set Output file path

SaveFile = new File (Environment.getexternalstoragedirectory ()
            . Getcanonicalfile () + "/myvideo.mp4");
Recorder.setoutputfile (Savefile.getabsolutepath ());

----3.5 Preview Using Surfaceview

Recorder.setpreviewdisplay (Surfaceview.getholder (). Getsurface ());

Start recording----3.6

Recorder.prepare ();
Start recording
Recorder.start ();
Let the start button not be clicked, the Stop button can be clicked
startrecord.setenabled (false);
Stoprecord.setenabled (true);
IsRunning = true;

----3.7 Stop Recording

 Stop recording
recorder.stop ();
Releasing Resources
recorder.release ();
Recorder = null;
Set Start button can be clicked, stop button is not clickable
startrecord.setenabled (true);
Stoprecord.setenabled (FALSE);

Complete code:

 Package Com.xqx.mediarecorder.app;
  Import android.app.Activity;
  Import Android.media.MediaRecorder;
  Import Android.os.Bundle;
  Import android.os.Environment;
  Import Android.view.SurfaceHolder;
  Import Android.view.SurfaceView;
 Import Android.view.View;
 Import Android.widget.Button;
 Import Android.hardware.Camera;
 Import Java.io.File;
 Import java.io.IOException; public class Workrecorder extends activity implements Camera.previewcallback {//start recording, stop Recording button private button Startre
   Cord,stoprecord;
   Show preview of Surfaceview private Surfaceview Surfaceview;
   tag to determine whether Boolean isrunning = False is currently being recorded;
   Recording class private Mediarecorder recorder;
   Store files private file savefile;
     @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
     Setcontentview (R.layout.activity_work_recorder);
     Startrecord = (Button) Findviewbyid (R.id.startrecord);
     Stoprecord = (Button) Findviewbyid (R.id.stoprecord);Surfaceview = (Surfaceview) Findviewbyid (R.id.surview);
     OnCreate () initialization, certainly did not start recording at first, so the stop button is not clickable stoprecord.setenabled (false);
     Setting SURFACE does not need to maintain its own buffer Surfaceview.getholder (). SetType (Surfaceholder.surface_type_push_buffers);
     Set resolution Surfaceview.getholder (). Setfixedsize (,);
   Setting this component does not allow the screen to automatically turn off Surfaceview.getholder (). Setkeepscreenon (True); /** * Start Recording * @param view/public void Btnstartrecord (view view) {//First determine whether the video recording state is currently processed, only if it is not a recording state
         , you can begin recording if (!isrunning) {try {///create Mediarecorder Object recorder = new Mediarecorder ();
         Recorder.reset ();
         . Set the acquisition sound Recorder.setaudiosource (MediaRecorder.AudioSource.MIC);
         Setting up the collection Image Recorder.setvideosource (MediaRecorder.VideoSource.CAMERA);
         . Set the video, audio output format recorder.setoutputformat (MediaRecorder.OutputFormat.MPEG_); . Set the encoding format for audio Recorder.setaudioencoder (MediaRecorder.AudioEncoder.AAC);
         Sets the encoding format of the image Recorder.setvideoencoder (mediarecorder.videoencoder.h);
         Set stereo Recorder.setaudiochannels ();
         Set maximum video time unit: Millisecond recorder.setmaxduration ();
         Sets the size unit of the maximum recording, byte recorder.setmaxfilesize (*);
         The amount of data bits recorder.setaudioencodingbitrate () that the audio contains in one second;
         Set the selection angle, clockwise direction, because the default is the reverse, so that the image is the normal display, here is set to watch the saved video angle recorder.setorientationhint ();
         Set output file path//SaveFile = Fileutils.getmediarecoderfolder (this);
 SaveFile = new File (Environment.getexternalstoragedirectory (). Getcanonicalfile () + "/myvideo.mp");
 Recorder.setvideosize (,);
         Recorder.setvideoframerate ();
         Recorder.setoutputfile (Savefile.getabsolutepath ());
         Use Surfaceview to preview Recorder.setpreviewdisplay (Surfaceview.getholder (). Getsurface ());
         Recorder.prepare ();
         Start recording Recorder.start (); Let the start button not be clicked, the Stop button can be clicked Startrecord. setenabled (FALSE);
         Stoprecord.setenabled (TRUE);
       IsRunning = true;
       catch (IOException e) {e.printstacktrace ();
       /** * End Recording * @param view */public void Btnstoprecord (view view) {if (isrunning) {
       Stop recording recorder.stop ();
       Releasing resources recorder.release ();
       Recorder = null;
       Set Start button can be clicked, stop button is not clickable startrecord.setenabled (true);
     Stoprecord.setenabled (FALSE); @Override public void Onpreviewframe (byte[] data, Camera Camera) {}}}

This example is just a simple demo, for just contact Mediarecorder Audio Recording Coder Learning, there are some bugs and deficiencies, you coder can continue to expand

Insufficient:

1, only when the "Start recording" when the Surfaceview component can see the camera shot preview, otherwise it is a black, here you can see the CanEra class, adjust the corresponding

2, save the path, need to determine whether there is external storage, storage space is enough, the path does not exist, whether there are existing file names of the same files exist, and so on, set the name of the file, I am here fixed path fixed file name

3, the camera preview effect is 90 degrees rotation, here need everyone to see the Mediorecoder API to set

4, does not set the focus, the pixel is not clear, the camera width high distortion

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.